[Solved] change protocol of urls on webpage via javascript [closed]


As you know, the correct fix here is to fix those links server-side, ideally by removing the scheme entirely, to create scheme-relative URLs like this:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

But you’ve said you can’t do that.

So:

  • You can readily find all a elements via document.querySelectorAll.
  • You can easily loop through the result.
  • …and get their href via getAttribute (or the resolved URL via the href property)
  • …and update it if necessary (via setAttribute or the href property).
  • Similarly, script and link rel="stylesheet".

Here’s a simple example for links:

Array.prototype.forEach.call(
    document.querySelectorAll("a[href]"),
    function(link) {
        if (link.href.startsWith("http://")) {
            link.href = "https://" + link.href.substring(7);
        }
    }
);

Ensure that’s in a script tag at the end of </body> so that the elements exist as of when it runs.

Generalize as needed for img (the src property), script (the src property), link[rel=stylesheet] (the href property), … (Each of those is a valid CSS selector which will work with querySelectorAll.)

2

solved change protocol of urls on webpage via javascript [closed]