繁体   English   中英

在 AJAX 请求后执行 javascript 代码

[英]Execute javascript code after AJAX request

我已经为我的网站创建了一个与 cookie 横幅相关的插件,现在我想在用户接受 cookie 横幅后运行跟踪代码脚本。

我能够使用insertAdjacentHTML注入代码,现在我想弄清楚如何执行此代码以便触发相关的跟踪 cookie。

我见过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);

我该如何解决这种情况? 当然我也可以让页面重新加载,但这对我的访问者来说不是一个好的用户体验。

更新:

我正在按照评论中的建议使用此处给出的代码: Jquery cookie monitor

我现在能够看到 cookie 何时创建和修改,并相应地给出响应。

我目前正在使用警报来确保这一点,但现在我需要运行外部 JavaScript 代码,例如 Hotjar 或 Google Analytics 代码,如果它只是注入(我正在做的)将不会运行。

例如,这是我试图运行失败的 Hotjar JavaScript 代码:

<!-- 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>

我能够找到一个更简单的解决方案。

这是我用来注入各种脚本并让它们在插入后运行的代码:

// Remove comments and HTML tags using the replace function and a regular expression
var plainText = code_before_end_head[key_cod].replace(/<!--[\s\S]*?-->|<[^>]*>/g, '');

// Create a new script element
const script = document.createElement('script');

// Assigns an ID to the script element
script.id = 'gcbi-'+key_con;

// Assigns the code to be executed to the script element
script.innerHTML = plainText;

// Injects the script element into the head section of the document
document.head.appendChild(script);

无需使用 listenCookieChange 函数,因为一切都是通过 AJAX 完成的。

上面显示的代码只是在收到来自 PHP 文件的响应时插入到请求中。

我希望它能有所帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM