admin管理员组

文章数量:1316645

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

<iframe width='650' height='365' src="" 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?

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

Share Improve this question edited Jul 19, 2016 at 8:57 Rory McCrossan 338k41 gold badges320 silver badges351 bronze badges asked Jul 19, 2016 at 8:53 JordynJordyn 1,1332 gold badges13 silver badges31 bronze badges 2
  • 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 Commented Jul 19, 2016 at 8:55
  • Just use <iframe src="//www.youtube./embed/y9kBixgYKzw" …> in the first place – Bergi Commented Jul 19, 2016 at 9:12
Add a ment  | 

4 Answers 4

Reset to default 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.

Are you trying to change the protocol of the URL in the iframe source? Or trying to redirect the ining 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.

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

src="//www.youtube./embed/y9kBixgYKzw"

Try it

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

本文标签: Convert all http to https using jQuery or JavascriptStack Overflow