Javascript,在离开页面前先做点事

时间:2018-07-30 09:25:13

标签: javascript onbeforeunload eventtrigger

由于新的GDPR法律,当用户继续在我们的网站上浏览时,这意味着他同意cookie,我们需要对其进行记录。

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

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

  • 记录Cookie
  • 启动要设置跟踪器的触发器

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

如果有人可以帮助我,也许我是在做错事

3 个答案:

答案 0 :(得分:0)

另一个问题,因为我使用一个事件来创建跟踪器,是否存在在重新加载页面之前不执行跟踪器的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');
});

答案 1 :(得分:-1)

从文档中:

  

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

https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

因此,您不应在此函数末尾进行=INDEX(C2:E4,MATCH(1,INDEX((A2:A4="mgr1")*(B2:B4="US"),0,1),0),MATCH("Feb",C1:E1,0))

答案 2 :(得分:-1)

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

Grizzly one's

警报原因,询问用户是否由于返回null或unbeunundefined中未定义的值而真的要离开网站,最终要求确认。

相关问题