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

javascript - How to ask confirmation when closing a window? - Stack Overflow

programmeradmin5浏览0评论

I want to pop up a message asking for confirmation if the user wants to leave the current page, exactly like stackoverflow does it when you are typing a question.

Could someone help me on this, by giving me a script or redirecting me to an answer (on this site or elsewhere) ?

Thanks

I want to pop up a message asking for confirmation if the user wants to leave the current page, exactly like stackoverflow does it when you are typing a question.

Could someone help me on this, by giving me a script or redirecting me to an answer (on this site or elsewhere) ?

Thanks

Share Improve this question asked Jan 25, 2010 at 14:07 Maxime ARNSTAMMMaxime ARNSTAMM 5,31411 gold badges55 silver badges76 bronze badges 2
  • Would it be inpolite to suggest that you just look at the source for stackoverflow? – Klaus Byskov Pedersen Commented Jan 25, 2010 at 14:09
  • Not to be rude but did you actually search for an answer first? – Aim Kai Commented Jan 25, 2010 at 14:11
Add a ment  | 

5 Answers 5

Reset to default 10

You could use the onbeforeunload event.

window.onbeforeunload = function() {
   return 'Are you sure that you want to leave this page?';
};

You need to handle the window's onbeforeunload event and return a confirmation message as a string.

onunload will not work here. Demo

window.onbeforeunload Seems to work for IE, but something like

window.onunload = function()
{
    if (confirm('Save changes?'))
        document.forms['form1'].submit();
};

Seems to work for all browsers.

You will have to store all the values of your fields in some variables & check them whenever use changes the page url or clicks on some link, to trap the page change event use page unload event.

Page unload event link/ sample http://help.dottoro./ljflhicd.php.

Doesn't this work?

<body onunload="return confirm('really quit?');">

Also for framesets by the way...

发布评论

评论列表(0)

  1. 暂无评论