Detect HTTP or HTTPS then force HTTPS in JavaScrip

2019-01-04 16:02发布

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

I have some codes for detecting the HTTP or HTTPS but I can't force it to use 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();
}

9条回答
混吃等死
2楼-- · 2019-01-04 16:41

Setting location.protocol navigates to a new URL. No need to parse/slice anything.

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

Firefox 49 has a bug where https works but https: does not. Said to be fixed in Firefox 54.

查看更多
放我归山
3楼-- · 2019-01-04 16:46
<script type="text/javascript">
        function showProtocall() {

            if (window.location.protocol != "https") {
                window.location = "https://" + window.location.href.substring(window.location.protocol.length, window.location.href.length);
                window.location.reload();
            }
        }
        showProtocall();
</script>
查看更多
神经病院院长
4楼-- · 2019-01-04 16:50

I have just had all the script variations tested by Pui Cdm, included answers above and many others using php, htaccess, server configuration, and Javascript, the results are that the script

<script type="text/javascript">        
function showProtocall() {
        if (window.location.protocol != "https") {
            window.location = "https://" + window.location.href.substring(window.location.protocol.length, window.location.href.length);
            window.location.reload();
        }
    }
    showProtocall();
</script> 

provided by vivek-srivastava works best and you can add further security in java script.

查看更多
闹够了就滚
5楼-- · 2019-01-04 16:58

How about this?

if (window.location.protocol !== 'https:') {
    window.location = 'https://' + window.location.hostname + window.location.pathname + window.location.hash;
}

Ideally you'd do it on the server side, though.

查看更多
你好瞎i
6楼-- · 2019-01-04 17:00

Hi i used this solution works perfectly.No Need to check, just use https.

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

greets BrAiNee

查看更多
做自己的国王
7楼-- · 2019-01-04 17:01

It is not good idea because you just temporary redirect user to https and browser doesn't save this redirect.

You describe task for web-server (apache, nginx etc) http 301, http 302

查看更多
登录 后发表回答