2

I'm trying to covert links in src tags to https://. More accurately Youtube iframes. For example:

<iframe width='650' height='365' src="http://www.youtube.com/embed/y9kBixgYKzw" frameborder="0" allowfullscreen></iframe>

I tried the below code with no luck:

function RedirNonHttps() {
    if (location.src.indexOf("https://") == -1) {
        location.src = location.src.replace("http://", "https://");
    }
}
<body onload="RedirNonHttps();">

Can someone point me out the correct way to do this?

Rory McCrossan
  • 306,214
  • 37
  • 269
  • 303
Jordyn
  • 1,063
  • 1
  • 12
  • 23
  • Doing this in JS is too late in the process as the request to the `http://` URL will already have been made. You need to make the change directly in your source code, or on the server before the HTML is served to the client – Rory McCrossan Jul 19 '16 at 08:55
  • Just use ` – Bergi Jul 19 '16 at 09:12

4 Answers4

3

In general, the example below show how it would work. Loop the elements by each and replace the source tag, as in your code:

$("iframe").each(function() {
    $(this).attr("src", $(this).attr("src").replace("http://", "https://"));
});

But keep in mind, this might be to late. The frames may be already loaded over http. As pointed out before, you have to do it on server side to be sure the content will be loaded over https.

eisbehr
  • 11,374
  • 7
  • 30
  • 56
2

Are you trying to change the protocol of the URL in the iframe source? Or trying to redirect the incoming request to the HTTPS counterpart?

If it is the latter, you may want to try a solution like this: Detect HTTP or HTTPS then force HTTPS in JavaScript

if (window.location.protocol != "https:")
    window.location.href = "https:" + window.location.href.substring(window.location.protocol.length);

You could run this in your head Javascript.

If you are trying to change the source of the iframe, I believe you will run into the issue that eisbehr has explained. That is, the external source has already loaded over HTTP.

Community
  • 1
  • 1
bgallz
  • 101
  • 6
0

Try replacing "https://" with just "//"

src="//www.youtube.com/embed/y9kBixgYKzw"
wrben
  • 73
  • 3
0

Try it

if (location.protocol != 'https:')
{
 location.href = 'https:' + window.location.href.substring(window.location.protocol.length);
}
dılo sürücü
  • 1,989
  • 1
  • 12
  • 19