有没有办法检测HTTP或HTTPS,然后强制使用HTTPS与JavaScript?

我有一些检测HTTP或HTTPS的代码,但我不能强迫它使用HTTPS:。

我使用window.location.protocol属性将站点设置为https:然后刷新页面,希望重新加载加载到浏览器中的新的https'ed URL。

if (window.location.protocol != "https:") {
   window.location.protocol = "https:";
   window.location.reload();
}

当前回答

设置的位置。协议导航到一个新的URL。不需要解析/切片任何东西。

if (location.protocol !== "https:") {
  location.protocol = "https:";
}

Firefox 49有一个错误,https可以工作,但https:不能。据说在Firefox 54中已修复。

其他回答

试试这个

if (location.protocol !== 'https:') {
    location.replace(`https:${location.href.substring(location.protocol.length)}`);
}

的位置。Href = blah将这个重定向添加到浏览器历史记录中。如果用户点击返回按钮,他们将被重定向回同一页面。最好使用位置。替换,因为它不会将此重定向添加到浏览器历史记录。

嗨,我用这个解决方案工作完美。不需要检查,只需使用https。

<script language="javascript" type="text/javascript">
document.location="https:" + window.location.href.substring(window.location.protocol.length, window.location.href.length);
</script>

设置的位置。协议导航到一个新的URL。不需要解析/切片任何东西。

if (location.protocol !== "https:") {
  location.protocol = "https:";
}

Firefox 49有一个错误,https可以工作,但https:不能。据说在Firefox 54中已修复。

下面的代码假设变量'str'包含你的http://....字符串。它检查是否为https,如果为true则不执行任何操作。但是如果是http,它会用https替换http。

if (str.indexOf('https') === -1) { STR = STR .replace('http', 'https') }

我喜欢这个问题的答案。但为了更有创意,我想再分享一种方法:

<script>if (document.URL.substring(0,5) == "http:") window.location.replace('https:' + document.URL.substring(5));</script>