Detect HTTPS with JavaScript [duplicate] Detect HTTPS with JavaScript [duplicate] javascript javascript

Detect HTTPS with JavaScript [duplicate]


Looking at how google analytics add their script to the page:

ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';

Then document.location.protocol would seem safe for all browsers.


You can use the non-standard

window.location.protocol 

In Firefox: MDC documentation

In IE, it seems to be

 document.location.protocol

MSDN documentation

I can't find reliable info on how this behaves on other browsers, but I expect they adhere to the quasi-standard of document.location.protocol.

Maybe the jQuery url plugin sorts this out without having to deal with cross-browser differences - I've never used it myself, but it looks promising:

jQuery.url.attr("protocol");


location.protocol works on all browsers.