简体   繁体   English

使用onbeforeunload的正确方法?

[英]Correct way to use onbeforeunload?

I am trying to post data when user arrives my page. 我试图在用户到达我的页面时发布数据。 This works in chrome and explorer, and also firefox, but however, on firefox, it strangely only works if user closes the page. 这在chrome,explorer和Firefox中都有效,但是在Firefox上,仅在用户关闭页面时才有效。 If they go back, or goes another site (by typing to address bar or whaever) it doesnt post the data. 如果他们回去了,或者去了另一个站点(通过在地址栏或其他地方键入内容),则不会发布数据。 My question is, what is the correct way to use onbeforeunload to post data ? 我的问题是,使用onbeforeunload发布数据的正确方法是什么?

$(window).bind('beforeunload', function () {

      $.post("track.php", {
         async: false,
         ip: ip,
         referer: referer,
         clicks: kactane2,
         scrolls: kactane,
         time: time,
         refid: refid,
         country: country, 
      });

});

There isn't a good way because that is not how onbeforeunload was meant to be used. 没有一个好方法,因为那不是onbeforeunload使用方式。

The correct way to use onbeforeunload is to listen for this event and then unload any data or resources you might be using because the user is leaving the page. 使用onbeforeunload的正确方法是侦听此事件,然后卸载由于用户离开页面而可能使用的任何数据或资源。 You should not use it to try to start new things. 您不应该使用它来尝试开始新事物。 According to the HTML5 specification showModalDialog() , alert() , confirm() and prompt() are explicitly not allowed and the idea is to give you a moment to clean up any event handlers, web workers and other stuff cleanly. 按照HTML5规范 showModalDialog() alert() confirm()prompt()明确不允许的,这个想法是给你一点时间来清理任何事件处理程序,网络工作者和其他的东西干净。

If an event handler is defined then the user may be presented with a page that says "Are you sure you want to leave?" 如果定义了事件处理程序,则可能会向用户显示"Are you sure you want to leave?" but for security reasons the form is generally not able to be customized, but it depends on the browser. 但出于安全原因,通常无法自定义表单,但取决于浏览器。

You will probably be better off setting the data in a cookie or something that can be done quickly and that is only occurring in the browser, then just look for that data on the next page load. 您最好将数据设置为cookie或可以快速完成且仅在浏览器中进行的操作,然后在下一页加载时查找该数据。

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

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