Javascript catch mixed content error to handle gracefully
Asked Answered
G

3

6

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

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

Geulincx answered 26/7, 2017 at 13:6 Comment(0)
A
1

There is no way to catch mixed content warnings, as they have no relation to JavaScript and are handled by your browser instead.

What you can do instead is use Upgrade-Insecure-Requests header to prevent browser from loading unsafe content entirely. 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:

<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. This is probably the best solution, as this gives you full overview of what data your website it trying to load.

Angry answered 30/4, 2021 at 12:7 Comment(1)
Will the Upgrade-Insecure-Requests always decide to choose HTTP over HTTPS? Though.Wellestablished
W
1

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.

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

First off mixed content will occur when such initial-based HTML is transferred over the network through a secure HTTPS connection. Although, the problem arises when other resources as you stated such as:

  • Images
  • Videos
  • Stylesheets
  • Scripts

...are loaded over an insecure HTTP connection. 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. And the main issue is the initial request was originally sent over secure over the HTTPS protocol.

Note: Before continuing, when requesting any of these subresources overusing the insecure HTTP transfer protocol, will open up vulnerabilities of the entire origin site. 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. 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. So in conclusion, it will disregard the HTTP resource.

Content Security Policy (CSP)

You need to reference the below section of https://web.dev - Fixing Mixed Content linked here. 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. Which has replaced the X-Content-Security-Policy older policy.

My suggestion is to make use of the <meta> HTML element. This will allow you to customize which domains you trust in regards to CSP in general and implement different customizations using this element.

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.

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?, which was referenced in this post. Hope I was of some help.

Complete References List:

Wellestablished answered 6/5, 2021 at 16:4 Comment(0)
T
0

What I do whenever dealing with mixed content is updating the .htaccess file with the following:

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.

Testamentary answered 6/5, 2021 at 18:32 Comment(1)
in my case, the 3rd party library was having some issue, it was actually downgrading to HTTP. And we changed the code to load it from a proper CDN instead. So I'd like to monitor for this kind of errorsMears

© 2022 - 2024 — McMap. All rights reserved.