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

onbeforeunload - Call a function on page refresh using Javascript - Stack Overflow

programmeradmin1浏览0评论
function warnuser()
{
    return "Don't refresh the page.";
}

window.onbeforeunload = warnuser;

If the user refreshes the page and the user clicks 'leave this page' on confirmation box, i want to call a javascript function , otherwise not! I am confused about how to do that. Thank you

function warnuser()
{
    return "Don't refresh the page.";
}

window.onbeforeunload = warnuser;

If the user refreshes the page and the user clicks 'leave this page' on confirmation box, i want to call a javascript function , otherwise not! I am confused about how to do that. Thank you

Share Improve this question edited Jul 1, 2012 at 23:38 ThiefMaster 319k85 gold badges607 silver badges646 bronze badges asked Jul 1, 2012 at 21:53 RajatRajat 3231 gold badge8 silver badges19 bronze badges 4
  • 3 If refreshing the page causes a problem, you should probably be focusing your efforts on making it not be a problem instead of preventing people from doing it in the first place. – Quentin Commented Jul 1, 2012 at 21:55
  • I agree with @Quentin, you probably need to be conforming to the "Post Redirect Get" paradigm. – Travis J Commented Jul 1, 2012 at 21:56
  • 1 @jezternz - There is always a way! :) But going down the hack path will forever dominate your codebase :P – Travis J Commented Jul 1, 2012 at 21:57
  • I need to do that...m half the way in finishing this....just want to know how can i know whether user clicked on 'Stay on this page' or 'leave this page' and perform some action accordingly. – Rajat Commented Jul 1, 2012 at 22:09
Add a ment  | 

2 Answers 2

Reset to default 1

You need to intercept the F5 key press and setup the onbeforeunload handler only in that case:

document.addEventListener('keydown', function(e) {
    if(e.which == 116) {
        window.onbeforeunload = function() {
            window.onbeforeunload = null;
            return "Do you really want to refresh the page?";
        }
    }
}, false);

Demo: http://jsfiddle/ejDrq/

Note that this does not work if the user clicks the Refresh button. It is impossible to intercept this.

If you have control of the server side which is hosting the page then you can handle this logically with a semaphore (wiki:semaphore). Basically it is a spinning lock which would be implemented in their server side session. Resetting the page state if they have entered and not exited in a safe manner. Naturally, as with all spinning locks, there would have to be a safe state to clear the lock out.

发布评论

评论列表(0)

  1. 暂无评论