简体   繁体   English

如何检测浏览器扩展是否阻止了 HTTP 请求?

[英]How to detect if HTTP requests are blocked by a browser extension?

I am trying to detect if a user is using some kind of extension in his browser that could prevent my site from working properly and if so, display a message for the user.我试图检测用户是否在其浏览器中使用某种扩展程序,这可能会阻止我的网站正常工作,如果是,则为用户显示一条消息。

I am testing with an extension called uMatrix , but there are others with a similar approach.我正在测试一个名为uMatrix的扩展,但还有其他类似的方法。

My problem is, that kind of extension will block my HTTP request, but that doesn't return a proper status code (like 403, 404, 500, etc).我的问题是,这种扩展会阻止我的 HTTP 请求,但不会返回正确的状态代码(如 403、404、500 等)。 Instead, when I catch my request, I just get a相反,当我catch我的请求时,我只会得到一个

Error: Network Error错误:网络错误

at [my file name and line number here]在 [我的文件名和行号]

at XMLHttpRequest.handleError (xhr.js:83)在 XMLHttpRequest.handleError (xhr.js:83)

I believe this same error would be thrown in other circumstances, like lack of internet connection, so I can't assume this Network Error means that the user has a "HTTP request blocker".我相信在其他情况下也会抛出同样的错误,比如缺乏互联网连接,所以我不能假设这个Network Error意味着用户有一个“HTTP 请求阻止程序”。

I was reading a lot about identifying AdsBlocker on this thread and other places, but I don't think it applies to my issue.我在这个线程和其他地方阅读了很多关于识别 AdsBlocker 的文章,但我认为它不适用于我的问题。

Any ideas on how to identify that a user is blocking my HTTP Requests?关于如何识别用户阻止我的 HTTP 请求的任何想法? (Either on purpose or through a browser extension) (有意或通过浏览器扩展)

I thought I would share here the solution I found, even though I don't think that's the best answer yet.我想我会在这里分享我找到的解决方案,尽管我认为这还不是最好的答案。

I am using Axios for my API requests and I found this thread here:我将 Axios 用于我的 API 请求,我在这里找到了这个线程:

https://github.com/axios/axios/issues/383#issuecomment-234079506 https://github.com/axios/axios/issues/383#issuecomment-234079506

What they suggest it's to check if the response has a status (but in latest Axios, they don't even return a response ).他们建议检查response是否具有状态(但在最新的 Axios 中,他们甚至不返回response )。 If not, it means the server was never reached.如果没有,则表示从未访问过服务器。 That could still mean that there is no internet connection, not necessarily an extension blocked the request.这仍然可能意味着没有互联网连接,不一定是扩展程序阻止了请求。 So I adjusted my message to cover both scenarios.所以我调整了我的信息以涵盖这两种情况。

My final code was something like this:我的最终代码是这样的:

// Note the use of "HEAD", since that will be faster than a "GET"
axios.head(server_url_for_testing).catch(function(error) {
  if (!error.response) {
    // Display my warning message
  }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM