Detect HTTPS with JavaScript.

This is a short tutorial on how to detect HTTPS / SSL using JavaScript. In order to do this, we will be using the location.protocol property.

This may come in handy if you need to dynamically create HTTP links or whatnot.

Take a look at this custom JavaScript function, which will return a boolean TRUE value if HTTPS has been detected:

The function above checks to see if the location.protocol property contains the string https:. If it does, this function will return a TRUE value. If not, it will return a boolean FALSE value.

You can use this function like so:

Thankfully, the Location interface and its location.protocol property is supported by all major browsers. As a result, this function should be able to detect the correct protocol in the vast majority of cases.

If you dump out the location.protocol property to the browser console, you will get a clearer idea of what it contains:

For example, on a non-HTTPS / plaintext HTML page, this will result in the following: “http:”

Facebook Comments