检测 HTTP 或 HTTPS 然后在 JavaScript 中强制使用 HTTPS [英] Detect HTTP or HTTPS then force HTTPS in JavaScript

查看:43
本文介绍了检测 HTTP 或 HTTPS 然后在 JavaScript 中强制使用 HTTPS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以检测 HTTP 或 HTTPS,然后通过 JavaScript 强制使用 HTTPS?

Is there any way to detect HTTP or HTTPS and then force usage of HTTPS with JavaScript?

我有一些用于检测 HTTP 或 HTTPS 的代码,但我不能强制它使用 https: .

I have some codes for detecting the HTTP or HTTPS but I can't force it to use https: .

我正在使用 window.location.protocol 属性将站点设置为 https: 然后刷新页面以重新加载新的 https 链接加载到浏览器中.

I'm using the window.location.protocol property to set whatever the site is to https: then refresh the page to hopefully reload a new https'ed URL loaded into the browser.

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

推荐答案

试试这个

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

location.href = blah 将此重定向添加到浏览器历史记录中.如果用户点击后退按钮,他们将被重定向回同一页面.最好使用 location.replace 因为它不会将此重定向添加到浏览器历史记录中.

location.href = blah adds this redirect to the browser history. If the user hits the back button, they will be redirected back to the the same page. It is better to use location.replace as it doesn't add this redirect to the browser history.

这篇关于检测 HTTP 或 HTTPS 然后在 JavaScript 中强制使用 HTTPS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆