52

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 Answers3

80

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:';
}
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • 2
    window. is the global scope and hence not needed, just a side-note. – jishi Nov 11 '08 at 23:09
  • didnt know about .protocol, simpler than my solution – Neil Aitken Nov 11 '08 at 23:10
  • 1
    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. – bobince Nov 12 '08 at 01:34
  • 1
    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. – tvanfosson Nov 22 '08 at 01:00
  • [This method](https://stackoverflow.com/a/52011220/1541397) should be used instead when possible, because this answer is inaccurate when there are problems with certificate. – David Callanan Jan 16 '20 at 10:46
11

As google analytics taught me:

if ("https:" == document.location.protocol) {
    /* secure */
} else {
    /* unsecure */
}
sth
  • 222,467
  • 53
  • 283
  • 367
Rod
  • 2,046
  • 2
  • 20
  • 24
3

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

  • 1
    A warning from the linked page: "Locally delivered files such as `http://localhost` and `file://` paths are considered to have been delivered securely." – SAGExSDX Jan 30 '20 at 23:29
  • 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? – user9645 Feb 07 '23 at 17:48