user3605780 user3605780 - 8 days ago 5
jQuery Question

change protocol of urls on webpage via javascript

Some of our urls on the pages are still in http and we cannot get this correct at the server side. Is there some javascript code to rewrite all urls with http:// to // or https://?

EDIT:

By testing with the anwser of T.J. Crowder I got all the "a href" to be replaced.

However I had a lot of different places where urls where of images i.e.

<header class="category_header init_bg_mobile" data-bg="//test.jpg" data-bg-md="http://test2.jpg" data-bg-xs-2x="http://test.jpg" >


So I made a mix of his anwser and This anwser.

<script>

(function(){
Array.prototype.forEach.call(

document.body.innerHTML = document.body.innerHTML.replace('http://', '//');

)();

</script>


This does the trick for now.

A side note, I don't think this is good practice since it changes every single place "http://" is on the page, which can also rewrite it if it is intented in the text. However it does the trick for now.

Answer

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="//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.)