window.onbeforeunload = function() { if (not_saved) if (confirm('Changes will not be saved')) return true; return false; }
但无论用户点击什么,结果都是一样的 – 愚蠢的硬编码对话框询问他们是否要离开页面或留在页面上.我想问他们的是他们是想留下还是离开,如果他们想留下什么,如果他们想要离开,他们就会离开.这甚至可能吗?我可以看到浏览器如何限制网站可以做些什么来保持用户在页面上,但我想我已经看到一些网站(我认为Google Docs)有很好的文明对话框.
解决方法
window.onbeforeunload = function(e) { return 'Dialog text here.'; };
文档:
> https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload
> http://dev.w3.org/html5/spec-LC/history.html#unloading-documents
Note that in Firefox 4 and later the returned string is not displayed to the user.
If the returnValue attribute of the event object is not the empty string,or if the event was canceled,then the user agent should ask the user to confirm that they wish to unload the document. The prompt shown by the user agent may include the string of the returnValue attribute,or some leading subset thereof. (A user agent may want to truncate the string to 1024 characters for display,for instance.)