在不打开弹出窗口的情况下检测被阻止的弹出窗口

2022-01-20 00:00:00 popup jquery javascript

关于如何检查弹出窗口是否在我的浏览器上被阻止"这个问题已被多次提出,我发现的所有解决方案都提出了一个解决方案,即打开一个新的弹出窗口进行测试.

This question has been raised many times on "How to check if the popup is blocked on my browser or not" and all the solutions that i found have proposed a solution where a new popup window is opened for testing.

参考资料:

  1. "检测 Chrome 中被阻止的弹出窗口"

"如何检测浏览器是否阻止了弹出窗口?"

等等.

我想知道是否有可能知道一个被阻止的弹出窗口,而无需实际打开一个.

I would like to know if there is any possibility of knowing a blocked popup, without actually opening one.

由于许多原因,测试弹出窗口可能需要一段时间才能关闭,这在您的应用程序的起始页上看起来很丑.

Because due to many reasons the test pop up may take time to close, which looks ugly on start-page of your application.

例如,如果我们可以使用来自客户端的请求标头中的任何内容,了解弹出首选项等,就像我们可以获得语言首选项一样.

For example if we could use anything from the request header from the client, to know the popup preferences etc like we can get for the language preferences.

这将是一个巨大的帮助.谢谢

It'll be a huge help. Thanks

推荐答案

据我所知,弹出窗口拦截器的工作原理是覆盖 window.open 函数,并且在大多数情况下返回 null.所以一种方法是检测 window.open 是否仍然是 nativ 函数.

As far as I know, popup blockers works by overwrite a window.open function and in most cases return a null. So one way is to detect if window.open is still nativ function.

您可以使用 toString 方法对其进行测试,该方法返回 [native code] 作为该函数的主体.toString 在旧的 IE 中不起作用,所以使用 ''+ 来转换函数.

You can test that with toString method, which return [native code] as a body of that function. toString not work in old IE, so instead of that use ''+ to convert function.

var havePopupBlockers = ('' + window.open).indexOf('[native code]') === -1;

这不是灵丹妙药,但可以检测潜在风险.我在 Chrome、FF、IE8 和 IE9 上使用一些不同的弹出窗口拦截器和作品进行了测试.

This is not silver bullet, but can detect potential risk. I test this on Chrome, FF, IE8 and IE9 with some various popup blockers and works.

相关文章