简体   繁体   English

Javascript 捕获混合内容错误以优雅地处理

[英]Javascript catch mixed content error to handle gracefully

Is there a way to globally catch mixed content errors?有没有办法全局捕获混合内容错误?

To be clear: I don't want to allow the insecure content, all I want to do is handle the error gracefully.要明确:我不想允许不安全的内容,我想做的就是优雅地处理错误。

Backstory: I'm integrating programmatic ads, that is i have to include some script tag, which returns some more JavaScript, which can load even more resources, etc...背景故事:我正在集成程序化广告,也就是说我必须包含一些脚本标签,它返回一些更多的 JavaScript,它可以加载更多的资源,等等......

It is impossible for me to control, what's coming to my website and sometimes those resources include http resources, which throw a mixed content error.我无法控制进入我网站的内容,有时这些资源包括 http 资源,这会引发混合内容错误。 I#m then left with an empty ads container, which looks kind of ugly.然后我留下了一个空的广告容器,看起来有点难看。 Also, I could try to resell this ad-space, since the first try failed.此外,我可以尝试转售此广告空间,因为第一次尝试失败。

I already tried window.onerror, but with no avail.我已经尝试过 window.onerror,但无济于事。

There is no way to catch mixed content warnings , as they have no relation to JavaScript and are handled by your browser instead.无法捕获混合内容警告,因为它们与 JavaScript 无关,而是由您的浏览器处理。

What you can do instead is use Upgrade-Insecure-Requests header to prevent browser from loading unsafe content entirely.您可以做的是使用Upgrade-Insecure-Requests标头来防止浏览器完全加载不安全的内容。 And, depending on your use case, you may use MutationObserver to react to changes in your HTML, or listen to Error Events on document.body during capture phase to react to errors:而且,根据您的用例,您可以使用MutationObserver对 HTML 中的更改做出反应,或者在捕获阶段监听document.body上的错误事件以对错误做出反应:

<html>
  <head>
    <meta
      http-equiv="Content-Security-Policy"
      content="upgrade-insecure-requests"
    />
  </head>

  <body>
    <script>
      const el = document.createElement("img");
      el.src = "http://unsafeimg";
      document.body.appendChild(el);
      document.body.addEventListener(
        "error",
        (err) => {
          console.log("Failed to load\n", err.target);
        },
        /* Notice the true value here. It is required because Error Events do not bubble */
        true
      );
    </script>
  </body>
</html>

Another option would be to set up a Service Worker to intercept and handle insecure requests.另一种选择是设置一个Service Worker来拦截和处理不安全的请求。 This is probably the best solution, as this gives you full overview of what data your website it trying to load.这可能是最好的解决方案,因为这可以让您全面了解网站尝试加载的数据。

Sounds like you are having an issue specifically revolving around fixing mixed content policies.听起来您遇到了一个专门围绕修复混合内容策略的问题。 There are many approaches to tackle and arrive at a solution.有许多方法可以解决并得出解决方案。

My recommendation is to go off some documentation provided and referenced by Google : https://web.dev - Fixing Mixed Content .我的建议是关闭一些由Google提供和引用的文档: https://web.dev-Fixing Mixed Content

Mixed content occurs when initial HTML is loaded over a secure HTTPS connection, but other resources (such as images, videos, stylesheets, scripts) are loaded over an insecure HTTP connection.当初始 HTML 通过安全的 HTTPS 连接加载,但其他资源(如图像、视频、样式表、脚本)通过不安全的 HTTP 连接加载时,会出现混合内容。 This is called mixed content because both HTTP and HTTPS content are being loaded to display the same page, and the initial request was secure over HTTPS.这称为混合内容,因为正在加载 HTTP 和 HTTPS 内容以显示同一页面,并且初始请求通过 HTTPS 是安全的。

First off mixed content will occur when such initial-based HTML is transferred over the network through a secure HTTPS connection.当这种基于初始的 HTML 通过安全 HTTPS 连接在网络上传输时,首先会出现混合内容。 Although, the problem arises when other resources as you stated such as:虽然,当您所说的其他资源时会出现问题,例如:

  • Images图像
  • Videos视频
  • Stylesheets样式表
  • Scripts脚本

...are loaded over an insecure HTTP connection. ...通过不安全的 HTTP 连接加载。 This is the definition of a mixed content issue described.这是所描述的混合内容问题的定义。 It is because of an issue pertaining to assets both HTTP and HTTPS content that is being requested and loaded to display on the website of the desired origin.这是因为 HTTP 和 HTTPS 内容被请求和加载以显示在所需来源的网站上的资产存在问题。 And the main issue is the initial request was originally sent over secure over the HTTPS protocol.主要问题是最初的请求最初是通过 HTTPS 协议安全发送的。

Note : Before continuing, when requesting any of these subresources overusing the insecure HTTP transfer protocol, will open up vulnerabilities of the entire origin site.注意:在继续之前,当请求这些子资源中的任何一个过度使用不安全的 HTTP 传输协议时,将打开整个源站的漏洞。 Such vulnerability attacks are named on-path attacks.此类漏洞攻击称为路径上攻击。

Depending on the browser your website user base is primarily targeting, there are fixes and preventions to take note of being rolled out by browsers such as Google Chrome.根据您的网站用户群主要针对的浏览器,有一些修复和预防措施需要注意由 Google Chrome 等浏览器推出。 Which will upgrade passive mixed content where it is possible.这将在可能的情况下升级被动混合内容。 Such a process will be deciding if the resource asset is available over HTTPS, but determine if it was created to be served over the HTTP protocol, the browser will load the HTTPS version instead.这样的过程将决定资源资产是否可通过 HTTPS 获得,但确定它是否是为通过 HTTP 协议提供服务而创建的,浏览器将改为加载 HTTPS 版本。 So in conclusion, it will disregard the HTTP resource.所以总而言之,它将忽略 HTTP 资源。

Content Security Policy (CSP)内容安全策略 (CSP)

You need to reference the below section of https://web.dev - Fixing Mixed Content linked here.您需要参考以下链接的https://web.dev - Fixing Mixed Content部分。 It will allow you to utilize a browser-based implementation that may be used to solve and manage mixed content issues.它将允许您利用基于浏览器的实现来解决和管理混合内容问题。 Which allows and opens up opportunities for different enforcement policies to be implemented.这允许并为实施不同的执法政策提供了机会。

  • To enable CSP, you have the opportunity to set up your site to return the Content-Security-Policy HTTP header.要启用 CSP,您有机会设置您的站点以返回Content-Security-Policy HTTP 标头。 Which has replaced the X-Content-Security-Policy older policy.它取代了X-Content-Security-Policy旧策略。

My suggestion is to make use of the <meta> HTML element.我的建议是使用<meta> HTML 元素。 This will allow you to customize which domains you trust in regards to CSP in general and implement different customizations using this element.这将允许您自定义您通常信任的 CSP 域,并使用此元素实现不同的自定义。

This is an example where you do wish to allow any resource content from a trusted domain, and you may use alternative formatting to allow sub-domains and other aspects to grant desired outcomes.这是一个示例,您确实希望允许来自受信任域的任何资源内容,并且您可以使用替代格式来允许子域和其他方面授予所需的结果。 Notice the formatting, following the subdomain setting.注意子域设置之后的格式。

Content-Security-Policy: default-src 'self' example_trusted.com *.example_trusted.com

So when utilizing this, you may take an approach for certain resources such as advertisements or images you decide to trust, but must be set up appropriately.因此,在利用此功能时,您可以对某些资源(例如您决定信任的广告或图像)采取某种方法,但必须进行适当的设置。

One vague example might be, without an asterick:一个模糊的例子可能是,没有星号:

content="default-src 'self' https://example.com http://example.com:80/images/"

This concludes a result conclusive of:得出以下结论:

https://example.com # Correct
http://example.com/images/ # (Missing) Incorrect Port 
http://example.com:80/images/image.jpg - Correct Port
https://example.com:81 # (Missing) Incorrect Port

You may use approaches like these referenced here at Mozilla - Content-Security-Policy , which may help form a solution.您可以使用Mozilla - Content-Security-Policy 中引用的这些方法,这可能有助于形成解决方案。

Or just go completely vulnerable.或者只是变得完全脆弱。 content="default-src * 'unsafe-inline' 'unsafe-eval'"

Many references on StackOverflow such as How does Content Security Policy (CSP) work? StackOverflow 上的许多参考资料,例如内容安全策略 (CSP)如何工作的? , which was referenced in this post. ,这在这篇文章中被引用。 Hope I was of some help.希望我有所帮助。

Complete References List:完整的参考列表:

What I do whenever dealing with mixed content is updating the .htaccess file with the following:每当处理混合内容时,我所做的就是使用以下内容更新 .htaccess 文件:

Header always set Content-Security-Policy: upgrade-insecure-requests

That should by take care of the mixed content and make sure that you load everything trough HTTPS.这应该通过处理混合内容并确保您通过 HTTPS 加载所有内容。

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

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