最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - onbeforeunload not working at all - Stack Overflow

programmeradmin9浏览0评论

I have this code:

(function() {
      window.onbeforeunload = function () {
          alert("hi")
          console.log("unloading");
      };
})();

I also have this code:

window.addEventListener("beforeunload", function() {
   alert("hi")
   console.log("unloading")
});

None of them seem to work. All I want to do is log when the user tries to leave the page, but this isn't happening (latest Chrome, latest Firefox, Edge....), can anybody shed some light on why it's not working?

I have this code:

(function() {
      window.onbeforeunload = function () {
          alert("hi")
          console.log("unloading");
      };
})();

I also have this code:

window.addEventListener("beforeunload", function() {
   alert("hi")
   console.log("unloading")
});

None of them seem to work. All I want to do is log when the user tries to leave the page, but this isn't happening (latest Chrome, latest Firefox, Edge....), can anybody shed some light on why it's not working?

Share Improve this question asked Jun 3, 2016 at 11:38 Mario StoilovMario Stoilov 3,4475 gold badges33 silver badges51 bronze badges 1
  • This works nicely, anyway alert() is not showing up. I guess it's blocked in that state jsfiddle/tbnnpz56/2 (Hit run multiple times and watch the console) – Brain Foo Long Commented Jun 3, 2016 at 11:44
Add a ment  | 

4 Answers 4

Reset to default 3

Since 25 May 2011, the HTML5 specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event. See the HTML5 specification for more details. Note also that various mobile browsers ignore the result of the event (that is, they do not ask the user for confirmation). Firefox has a hidden preference in about:config to do the same. In essence this means the user always confirms that the document may be unloaded.

Source

Also, use return statement to prompt user before leaving

window.addEventListener("beforeunload", function() {
   return "hi";
});

Do it this way:

  window.onbeforeunload = function (e) {
          console.log("unloading");
          return "Hi";
      };

That will alert Hi when page unloads and also prints unloading in console

function myFunction() {
    return "Write something clever here...";
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body onbeforeunload="return myFunction()">
  
  </body>

You have to return from the onbeforeunload:

(function() {
  window.onbeforeunload = function () {
      alert("hi")
      console.log("unloading");
      return null;
      };
    })();
发布评论

评论列表(0)

  1. 暂无评论