Javascript,在离开页面之前做些什么

Javascript,在离开页面之前做些什么,javascript,onbeforeunload,eventtrigger,Javascript,Onbeforeunload,Eventtrigger,由于新的GDPR法律,当用户继续在我们的网站上导航时,这意味着他同意cookies,我们需要记录这一点 因此,我需要能够在用户离开页面、跟踪链接或验证表单之前执行一些操作。我该怎么做 我尝试使用window.onbeforeunload,但这会触发一个警报,询问用户是否真的想离开网站。在离开页面之前,我必须执行两个操作: 记录曲奇 启动一个触发器来设置跟踪器 window.onbeforeunload = function (e) { // Record the coo

由于新的GDPR法律,当用户继续在我们的网站上导航时,这意味着他同意cookies,我们需要记录这一点

因此,我需要能够在用户离开页面、跟踪链接或验证表单之前执行一些操作。我该怎么做

我尝试使用window.onbeforeunload,但这会触发一个警报,询问用户是否真的想离开网站。在离开页面之前,我必须执行两个操作:

  • 记录曲奇
  • 启动一个触发器来设置跟踪器

        window.onbeforeunload = function (e) {
            // Record the cookie
            // Launch a trigger to add the trackers
            return true;
        };
    

如果有人能从文档中帮我一把,也许我犯了个错误:

当此事件返回(或将returnValue属性设置为)null或undefined以外的值时,将提示用户确认页面卸载


因此,您不应该执行
返回true的操作

在离开页面之前,始终可以使用window.onbeforeunload()调用函数:


警报原因,询问用户是否真的想离开网站,因为onbeforeunload返回的值不是null或undefined,最后要求确认。

另一个问题,因为我使用事件创建我的跟踪器,我的跟踪器的eventListener,在重新加载页面之前是否不会执行

window.onbeforeunload = function (e) {
    document.dispatchEvent(new Event('tracker.launch'));
};
我的事件监听器

 document.addEventListener('tracker.launch', function() {
    <!-- Google Analytics -->
    (function(i,s,o,g,r,a,m){ i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
            m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
});
document.addEventListener('tracker.launch',function()){
(函数(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]| |函数(){
(i[r].q=i[r].q | |[]).push(参数)},i[r].l=1*新日期();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(窗口、文档、“脚本”和https://www.google-analytics.com/analytics.js","ga",;
});

事实上,正如我提到的,如果用户继续在网站上导航,这意味着他接受了cookie的使用。我同时这么做,法律规定如果用户继续导航,他们就接受了cookie,并且提到“通过继续访问此网站,您接受了cookie的使用”,如果他们愿意,他们仍然可以更改配置。很好,这项工作,我只有一个小问题。我现在在函数中调度了一个事件,它将创建我的跟踪器,但似乎没有处理该事件。页面之前已重新加载。
 document.addEventListener('tracker.launch', function() {
    <!-- Google Analytics -->
    (function(i,s,o,g,r,a,m){ i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
            m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
});