javascript - jquery prompt to save data onbeforeunload - Stack Overflow

admin2025-04-19  0

I want to remind users to save data on certain pages before navigating away from them (by clicking other links on the page) using the jquery ui dialog box. I know I need to use the onbeforeunload event to detect that a user is leaving the current page, then display the dialog. However, how do I allow navigation to continue to the selected url when the user clicks "Yes" on the dialog box, and stay on the current page when the user clicks "No"?

Thanks!

I want to remind users to save data on certain pages before navigating away from them (by clicking other links on the page) using the jquery ui dialog box. I know I need to use the onbeforeunload event to detect that a user is leaving the current page, then display the dialog. However, how do I allow navigation to continue to the selected url when the user clicks "Yes" on the dialog box, and stay on the current page when the user clicks "No"?

Thanks!

Share asked Jun 15, 2012 at 19:45 LalaLala 2371 gold badge7 silver badges12 bronze badges 3
  • 2 All you can do is ask the browser to ask the user to confirm that they want to leave the page, via the "onbeforeunload" mechanism. edit oh wait - you're asking how you find out that they decided not to leave your page, right? – Pointy Commented Jun 15, 2012 at 19:47
  • @Pointy My site already uses jquery ui dialogs, so I want to use that in this case too and be able to customize the dialog. But how do I code that clicking "Yes" means to continue with the original request and "No" signals staying on the same page? – Lala Commented Jun 15, 2012 at 22:08
  • Well that's the problem. When the user clicks "No", to stay on the page, the net effect is that nothing happens - it's like the user never clicked on whatever it was that triggered the event. Thus I don't think there is any way to directly do what you want, other than perhaps to try something like adding a class to the <body> in the "onbeforeunload" handler, and then having CSS respond with some change to the layout, or something. – Pointy Commented Jun 15, 2012 at 22:11
Add a ment  | 

2 Answers 2

Reset to default 3

You just need to assign function with prompt to window.onbeforeunload event, e.g.:

window.onbeforeunload =
    function() {
        return "Please make sure your data is saved."
    }

And the browser will automatically prompt the user with 2 choices: "Leave this page" and "Stay on this page"

After reading http://vidasp/jQuery-unload.html and Setting onbeforeunload on body element in Chrome and IE using jQuery, we hook into both window.onbeforeunload and bind to $(window).unload. Here's a jsFiddle with an example: http://jsfiddle/jtaylor/SqwV2

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745073405a283424.html

最新回复(0)