-4

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 with urls of images like:

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

Community
  • 1
  • 1
user3605780
  • 6,542
  • 13
  • 42
  • 67

1 Answers1

2

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

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Your solution seems to be the thing I want only it doesn't work for me. I updated my anwser for what I tried. – user3605780 Nov 29 '16 at 19:24
  • @user3605780: Look at the answer above, and look at the code in your question. They're not at all the same. In the answer, I'm finding the **elements** that need fixing and fixing them individually. In your question's code, you're trying to do a mass replace on `document.body.innerHTML`. A) That's a very bad idea, it completely tears down the document and builds it up, and B) You'd need a regex with the `g` flag for it to work (but see [A]). – T.J. Crowder Nov 30 '16 at 08:03