views:

1591

answers:

3

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.

+10  A: 

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
window. is the global scope and hence not needed, just a side-note.
jishi
didnt know about .protocol, simpler than my solution
Neil Aitken
Perfect. Thanks.
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
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
A: 

it is better if window is used this gives much clarity

A: 

As google analytics taught me:

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