Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

javascript - window.onbeforeunload executed on page refresh instead of on page close

I'm using window.onbeforeunload to pop up a confirm dialog when a close event occurs, but the confirm dialog appears on page refresh and doesn't execute on page close.

Here's the JavaScript code:

<script language="JavaScript">
    window.onbeforeunload = confirmWinClose();
    function confirmWinClose() {
        var confirmClose = confirm('Close?');
        return confirmClose;
    }    
</script>

I tried it on Chrome, Firefox and Internet Explorer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

PROBLEM WITH YOUR CODE:

the function will be called when you refresh, because on refresh the page is unloaded and then reloaded.

in your solution, you should also note that you are not assigning a function to window.onbeforeunload but you are assigning the return value of the function when you write

window.onbeforeunload = confirmWinClose();

which might also execute the function (based on where you place it in the javascript) whenever the assignment is done. For e.g.

function confirmWinClose() {
var confirmClose = confirm('Close?');
return confirmClose;
}

window.onbeforeunload = confirmWinClose();

the above code will execute the confirmWinClose function whenever this js is loaded.

(not your case as you have defined the function after call, so won't be executed on load, but you should remember this)

SOLUTION:

the below solution is working for close also

instead of your solution, i tried this

JS:

window.onbeforeunload = function() {
    var confirmClose = confirm('Close?');
    return confirmClose;
}

or

 window.onbeforeunload = confirmWinClose; //note the absence of calling parantheses

    function confirmWinClose() {
        var confirmClose = confirm('Close?');
        return confirmClose;
    }

this works as expected.

also note that you should return from the onbeforeunload explicitly.

even if you have to call a function, you should do

<script>
    window.onbeforeunload = function(e) {
       callSomeFunction();
       return null;
    };
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...