53

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 Answers 3

81

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:';
}
Sign up to request clarification or add additional context in comments.

5 Comments

window. is the global scope and hence not needed, just a side-note.
didnt know about .protocol, simpler than my solution
jishi: it's a style issue, arguably the ‘window.’ makes it clearer where the property is coming from. Conceivably you could also have a local/closure variable called ‘location’, in which case direct access to the global would get hidden.
I like the clarity of fully specifying the variable, but I can see where others might go for the shorthand and use the global scope.
This method should be used instead when possible, because this answer is inaccurate when there are problems with certificate.
11

As google analytics taught me:

if ("https:" == document.location.protocol) {
    /* secure */
} else {
    /* unsecure */
}

Comments

4

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

2 Comments

A warning from the linked page: "Locally delivered files such as http://localhost and file:// paths are considered to have been delivered securely."
I am seeing window.isSecureContext == true but the browser is saying "Not Secure" due to the certificate being invalid. Is there any way to check the page has the "closed lock" with no warnings?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.