javascript – 在window.onbeforeunload上的confirm()

前端之家收集整理的这篇文章主要介绍了javascript – 在window.onbeforeunload上的confirm()前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果用户想要使用未保存的表单数据离开页面,我想显示一个确认对话框.我有的是:
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.)

原文链接:https://www.f2er.com/js/155686.html

猜你在找的JavaScript相关文章