点击按钮后如何重新执行Cookie权限管理脚本?
场景说明
现有HTML模板加载了外部Cookie权限管理脚本,弹窗语言由<html>标签的lang属性控制:
<!DOCTYPE html> <html lang="fr"> <head> <script id="consentementCookiesScript" src="https://static.desjardins.com/fw/cookie/scriptCookie.js"></script> </head> <!-- 页面其他内容 --> </html>
同时实现了语言切换按钮及逻辑,点击后会修改<html>的lang属性:
<div id="toolbar" class="toolbar"> <div id="changeLangElement" style="color: white">Français</div> </div>
let currentLang = "fr"; changeLangElement.onclick = function () { currentLang = currentLang === "fr" ? "en" : "fr"; translatePage(currentLang); document.documentElement.lang = currentLang; };
问题
点击语言切换按钮后,如何重新执行Cookie权限脚本,让弹窗适配新的语言?
解决方案
方法1:移除并重新插入脚本标签
外部脚本加载后会自动执行,因此可以移除原有脚本元素,再创建一个相同src的新脚本标签插入到页面,触发重新加载执行:
let currentLang = "fr"; changeLangElement.onclick = function () { currentLang = currentLang === "fr" ? "en" : "fr"; translatePage(currentLang); document.documentElement.lang = currentLang; // 处理Cookie脚本重新加载 const oldScript = document.getElementById("consentementCookiesScript"); // 先移除已存在的Cookie弹窗(根据实际弹窗元素选择器调整) const cookiePopup = document.querySelector("[id*='cookie']"); if (cookiePopup) cookiePopup.remove(); // 创建新脚本标签 const newScript = document.createElement("script"); newScript.id = "consentementCookiesScript"; // 加时间戳避免缓存问题 newScript.src = `${oldScript.src}?t=${Date.now()}`; // 替换旧脚本 oldScript.parentNode.replaceChild(newScript, oldScript); };
方法2:调用脚本内置的重新初始化方法(如果有)
部分第三方Cookie管理脚本会暴露全局初始化方法,可直接调用实现语言适配。可以检查脚本是否提供类似reinitCookieConsent()的函数,若存在则直接在语言切换逻辑中调用:
changeLangElement.onclick = function () { currentLang = currentLang === "fr" ? "en" : "fr"; translatePage(currentLang); document.documentElement.lang = currentLang; // 若脚本提供重新初始化方法,直接调用 if (window.reinitCookieConsent) { window.reinitCookieConsent(); } };
注:如果方法2可行,优先使用,避免重复加载脚本带来的性能损耗;若脚本没有提供相关API,使用方法1即可。
内容的提问来源于stack exchange,提问作者analuspi
相关产品推荐
相关产品推荐

