How to make the “onbeforeunload” function be disabled for my own pages and work only for external ones?

我们两清 提交于 2019-12-23 04:28:06

问题


How to make the onbeforeunload function be disabled for my own pages and work only for external ones? How to make disable the code that OG Sean gave here: "Are you sure you want to leave this page?" functions for cancel and OK

<script>
    window.onbeforeunload = function(e) {
      return 'Are you sure you want to leave this page?  You will lose any unsaved data.';
    };
</script>

for all my subpages like (domain.com/shop; domain.com/about-us; and domain.com/contact), and enable it only for when you click on the "x" button to close the page? or when you try to type another URL in the address bar?

thanks in advance for the help :)


回答1:


Ok, so as promised I'll explain the solution given in this question : Confirm Leave on External Links in Wordpress.

The onbeforeunload event is special in the way that you can't cancel it or interfere in a meaningful way. If the user wants to leave, they'll leave and the browser won't let you interfere more than displaying a box. That is a security concern so you can't hold the user captive in your app.

what you CAN do is :

  1. have a onbeforeunload event that returns something (anything), so that when the user types a new address or otherwise navigates, you can warn them with the browser default box
  2. listen to every link in your app, and maybe prevent these with a custom box.
  3. if the user is sure, disable onbeforeunload so they don't have to click twice.

I've done a [small jsfiddle demonstrating this] (https://jsfiddle.net/6672ovrn/3/) (open the developper tools with [F12] to see the console output). The S.O. answer I linked up there works in the same way but it uses jquery's $("a").on("click", func(){}); to add the check automatically to all <a>, instead of having <a href="..." onclick="check" >go!</a>everywhere in the html.

Hope that helps.



来源:https://stackoverflow.com/questions/41814038/how-to-make-the-onbeforeunload-function-be-disabled-for-my-own-pages-and-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!