【问题标题】:Javascript, do something before leaving pageJavascript,在离开页面之前做一些事情
【发布时间】:2018-07-30 09:25:12
【问题描述】:

由于新的 GDPR 法,当用户继续在我们的网站上导航时,这意味着他同意 cookie,我们需要记录下来。

所以,我需要能够在用户离开页面、点击链接或验证表单之前做一些事情。我该怎么做?

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

  • 记录 cookie
  • 启动将设置跟踪器的触发器

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

如果有人能帮帮我,也许我犯了一个错误

【问题讨论】:

  • 实际上,正如我所提到的,如果用户继续在网站上导航,则表示他接受了 cookie 的使用。
  • 我两者都做,法律说他们继续浏览他们接受 cookie,并且提到“通过继续访问本网站,您接受使用 cookie”,他们可以如果他们愿意,仍然可以更改配置。

标签: javascript onbeforeunload eventtrigger


【解决方案1】:

另一个问题,因为我使用事件来创建我的跟踪器,是否存在我的跟踪器的 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');
});

【讨论】:

    【解决方案2】:

    来自文档:

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

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

    所以你不应该在这个函数的末尾加上return true;

    【讨论】:

    • 太好了,我现在只有一个小问题是在我调度一个事件的函数中,这将创建我的跟踪器,但似乎没有处理该事件页面重新加载之前。
    【解决方案3】:

    您总是可以在离开页面之前使用 window.onbeforeunload() 调用您的函数:

    window.onbeforeunload = function(){
      recordCookie(); //function call for recording cookies
      setTracker(); // function call for setting tracker
      return; // returning null
    };
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多