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
409 views
in Technique[技术] by (71.8m points)

javascript - Alerts when navigating away from a web page

When I try to close my Google docs tab with unsaved changes, this is what I get in my browser (FF 3.5).

Are you sure you want to navigate away from this page?

You have unsaved changes in this document. Click Cancel now, then 'Save' to save them. Click OK now to discard them.

Press OK to continue, or Cancel to stay on the current page.

My question is whether such alerts are part of the web app (gdocs for eg.) or are they given out by the browser? If latter, how is this done?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

By the browser. It's the beforeunload event handler that returns the customized text of the dialog, which is only the middle of the three paragraphs - the other two paragraphs as well as the text of the buttons cannot be customized or otherwise changed.

window.onbeforeunload = function(){ return 'Testing...' }

// OR

var unloadListener = function(){ return 'Testing...' };
window.addEventListener('beforeunload', unloadListener);

Will yield a dialog that says

Are you sure you want to navigate away from this page?

Testing...

Press OK to continue, or Cancel to stay on the current page.

You can nullify this by setting the handler to null

window.onbeforeunload = null;

// OR

window.removeEventListener('beforeunload', unloadListener);

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

...