如何以编程方式检测浏览器如何处理 window.close()?
不同的网络浏览器以不同的方式处理 window.close() 函数。 IE 会提示用户进行确认,而 Firefox 和 Safari 则无法接受它,除非窗口最初是用 Javascript 打开的,并在控制台中显示一条消息说明同样的内容。
我支持的我们组织内部使用的第三方 Web 应用程序在类似向导的一系列页面的末尾显示一个“关闭”按钮。这对于我们大多数用户使用的 IE 非常有效。然而,这在FF中显然失败了。我更愿意保留该按钮并使用 Javascript 来优雅地降级 UI,方法是不在任何不会执行 window.close() 的浏览器中显示该按钮。
根据经验,我会尽可能检查浏览器功能,而不是依赖基于浏览器检测的硬编码策略。有没有一种方法可以以编程方式检查对 window.close() 的支持,以便我可以确定是否应该首先显示该按钮?
Different web browsers handle the window.close() function differently. IE prompts the user for confirmation, while Firefox and Safari just fail to honor it unless the window was originally opened with Javascript and display a message saying as much in the console.
A third party web application used internally in our organization that I support displays a 'close' button at the end of a wizard-like series of pages. This works well for IE, which is what the majority of our users use. However, this obviously fails in FF. I'd prefer to leave the button in and use Javascript to gracefully degrade the UI by not displaying that button in any browser that will not perform the window.close().
As a rule of thumb, I try to check browser capability rather than relying on a hard-coded policy based on browser detection whenever possible. Is there a way to programmatically check the support for window.close() so I can determine whether the button should be displayed in the first place?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
演示:http://jsfiddle.net/ThinkingStiff/mnv87/
脚本:
注意
hasClose() 也会返回
false
。Try this:
Demo: http://jsfiddle.net/ThinkingStiff/mnv87/
Script:
Note
hasClose()
will also returnfalse
if popups are blocked.为什么不检查兼容性,如果兼容则追加?使用 jQuery:
由于 jQuery 是跨浏览器兼容的,所以它应该
Why not check compatibility, and then append if compatible? Using jQuery:
Since jQuery is cross browser compatible, it should
很简单。您的脚本应该尝试(或
try
)window.close
,如果尝试后它仍然存在 - 显示消息,并且可以选择删除/替换页面内容,或使用location.reload
不让您的用户有任何理由再停留在该页面。ps:请记住,从 JavaScript 关闭窗口是非常不礼貌的。所以你最好有一些充分的理由这样做;)
Very simple. Your script should try (or
try
) towindow.close
, and if its still alive after that try - show the message, and, optionally, erase/replace page content, or uselocation.reload
to not give your users any reason to stay at the page anymore.p.s.: keep in mind, closing windows from JavaScript is very impolite. So you better have some good reasons for doing it ;)