window.onbeforeunload上的confirm() [英] confirm() on window.onbeforeunload

查看:459
本文介绍了window.onbeforeunload上的confirm()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户想要使用未保存的表单数据离开页面,我想显示一个确认对话框。我拥有的是:

I want to show a confirmation dialog if the user wants to leave the page with unsaved form data. What I have is:

window.onbeforeunload = function() {
    if (not_saved) if (confirm('Changes will not be saved')) return true;
    return false;
}

但无论用户点击什么,结果都是一样的 - 愚蠢的硬编码的对话框,询问他们是否要离开页面或留在页面上。我想问他们的是他们是想留下还是离开,如果他们想留下什么,如果他们想要离开,他们就会离开。这甚至可能吗?我可以看到浏览器如何限制网站可以做些什么来保持用户在页面上,但我想我已经看到一些网站(我认为Google Docs)有很好的文明对话框。

But no matter what the user clicks, the result is the same - the stupid hardcoded dialog box that asks them whether they want to leave the page or stay on page. What I want to ask them is whether they want to stay or leave, and if they want to stay nothing happens, if they want to leave, they leave. Is this even possible? I can see how browsers want to limit what websites can do about keeping the users on the page, but I think I've seen some websites (Google Docs I think) having nice civilized dialog boxes.

推荐答案

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

请注意,在Firefox 4及更高版本中,返回的字符串不会显示给用户。

如果事件对象的returnValue属性不是空的
字符串,或者事件被取消,则用户代理应该询问用户
以确认他们是否要卸载该文档。
用户代理显示的提示可能包含returnValue属性的字符串或其某些前导子集。 (对于
实例,用户代理
可能希望将字符串截断为1024个字符。)

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.)

这篇关于window.onbeforeunload上的confirm()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆