用户接受Cookie横幅后,如何安全执行跟踪脚本?
我开发了一款Cookie横幅插件,希望用户接受Cookie后自动运行跟踪代码脚本。目前已经用insertAdjacentHTML注入了代码,但没法触发执行,也不想用有安全风险的eval()。现有代码如下:
http.onreadystatechange = function() { //Call a function when the state changes. if(http.readyState == 4 && http.status == 200) { var con_cod = JSON.parse(this.responseText); var consents = con_cod["consents"]; var head = document.getElementsByTagName("head")[0]; var code_before_end_head = con_cod["code_before_end_head"]; head.lastElementChild.insertAdjacentHTML("afterend", code_before_end_head); var now = new Date(); var time = now.getTime(); var expireTime = time + 24 * 60 * 60 * 1000; now.setTime(expireTime); document.cookie = cookie_name+'='+JSON.stringify(consents)+'; expires='+now.toUTCString()+'; SameSite=None; Secure; path=/'; } } http.send(params);
不想用刷新页面的方式,会影响用户体验。
更新:
已经用Cookie监测代码实现了Cookie创建/修改的监听,现在能通过弹窗验证,但运行Hotjar、Google Analytics这类外部脚本时遇到问题——仅注入代码无法执行。比如尝试注入以下Hotjar代码但失败:
<!-- Hotjar Tracking Code --> <script id="gcbi-statistics"> (function(h,o,t,j,a,r){ h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)}; h._hjSettings={hjid:7349271,hjsv:6}; a=o.getElementsByTagName('head')[0]; r=o.createElement('script');r.async=1; r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv; a.appendChild(r); })(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv='); </script>
解决方法
1. 替换insertAdjacentHTML,手动执行脚本
insertAdjacentHTML只会把代码作为静态HTML插入,不会触发脚本执行。你可以解析注入的HTML内容,提取脚本并创建新标签执行:
// 替换原代码中的insertAdjacentHTML部分 var tempContainer = document.createElement('div'); tempContainer.innerHTML = code_before_end_head; // 遍历所有脚本标签,逐个执行 var scripts = tempContainer.querySelectorAll('script'); scripts.forEach(script => { var newScript = document.createElement('script'); // 复制原脚本的属性(比如id、async等) Array.from(script.attributes).forEach(attr => { newScript.setAttribute(attr.name, attr.value); }); // 处理内联代码或外部资源 if (script.src) { newScript.src = script.src; } else { newScript.textContent = script.textContent; } head.appendChild(newScript); });
这种方式完全避开eval(),安全且能正确触发脚本执行。
2. 直接调用第三方脚本的初始化逻辑
像Hotjar这类跟踪脚本,不需要注入完整的HTML标签,用户同意后直接执行其初始化代码即可:
// 用户接受Cookie后直接执行Hotjar初始化 (function(h,o,t,j,a,r){ h.hj=h.hj||function(){(h.hj.q=h.hj.q||[]).push(arguments)}; h._hjSettings={hjid:7349271,hjsv:6}; a=o.getElementsByTagName('head')[0]; r=o.createElement('script');r.async=1; r.src=t+h._hjSettings.hjid+j+h._hjSettings.hjsv; a.appendChild(r); })(window,document,'https://static.hotjar.com/c/hotjar-','.js?sv=');
如果你的code_before_end_head包含多个第三方脚本,可以提前把它们的初始化逻辑整理成独立函数,用户同意后按需调用,比注入HTML更高效。
3. 结合Cookie监听触发执行
既然已经实现了Cookie监听,就可以在监测到用户同意的Cookie被设置时,触发上述脚本执行逻辑:
// 假设Cookie监听逻辑触发时调用此函数 function onConsentConfirmed() { // 在这里执行跟踪脚本初始化,比如上面的Hotjar代码,或解析注入脚本的逻辑 }
内容的提问来源于stack exchange,提问作者Matteo Feduzi
相关产品推荐
相关产品推荐

