使用jQuery或Javascript将所有http://转换为https://

Convert all http:// to https:// using jQuery or Javascript

本文关键字:转换 https http jQuery Javascript 使用      更新时间:2023-09-26

我正在尝试将src标记中的链接转换为https://。更准确地说,Youtube iframes。例如:

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

我尝试了以下代码,但没有运气:

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

有人能告诉我做这件事的正确方法吗?

通常,下面的示例显示了它的工作方式。通过each循环元素并替换源标记,如代码中所示:

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

但请记住,这可能为时已晚。这些帧可能已经通过CCD_ 3加载。如前所述,您必须在服务器端执行此操作,以确保内容将通过https加载。

您是否试图更改iframe源中URL的协议?或者试图将传入请求重定向到HTTPS对应方?

如果是后者,您可能需要尝试这样的解决方案:检测HTTP或HTTPS,然后在JavaScript 中强制HTTPS

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

你可以在你的头脑中运行这个Javascript。

如果你试图更改iframe的来源,我相信你会遇到eisbehr解释过的问题。也就是说,外部源已经通过HTTP加载。

尝试将"https://"替换为"//"

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

试试

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