How can I use JavaScript on the client side to det

2020-01-26 07:09发布

Is it possible to detect, on the client side, whether the user is using an encrypted page or not?

Put another way -- I want to know if the URL of the current page starts with http or https.

3条回答
看我几分像从前
2楼-- · 2020-01-26 07:23

As google analytics taught me:

if ("https:" == document.location.protocol) {
    /* secure */
} else {
    /* unsecure */
}
查看更多
▲ chillily
3楼-- · 2020-01-26 07:28

Use window.location.protocol to check if it is https:

function isSecure()
{
   return window.location.protocol == 'https:';
}

Alternatively you can omit specifying "window" if you don't have a locally scoped location.

function isSecure()
{
   return location.protocol == 'https:';
}
查看更多
在下西门庆
4楼-- · 2020-01-26 07:41

Second method for newest browsers:

var secure = window.isSecureContext;

or just get isSecureContext:

if (isSecureContext) {
   ...
}

More here: https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts#Feature_detection#Feature_detection

查看更多
登录 后发表回答