How can I use JavaScript on the client side to detect if the page was encrypted?

JavascriptHttpHttps

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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:';
}

Solution 2 - Javascript

As google analytics taught me:

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

Solution 3 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSimonView Question on Stackoverflow
Solution 1 - JavascripttvanfossonView Answer on Stackoverflow
Solution 2 - JavascriptRodView Answer on Stackoverflow
Solution 3 - JavascriptChris ZalcmanView Answer on Stackoverflow