In this tutorial, we are going to show you how to detect HTTPS / SSL using JavaScript.
The goal here is to check if the user is accessing our page over a secure connection.
To figure all of this out, we can use the location.protocol property.
Take a look at the custom JavaScript function below. This function will return a boolean TRUE value if the browser is using SSL:
//Checks to see if the current protocol is HTTPS / SSL function isHttps(){ return (document.location.protocol == 'https:'); }
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:
if(isHttps()){ console.log('HTTPS is enabled.'); } else{ console.log('HTTPS is not enabled.'); }
Thankfully, all major browsers support the Location interface and its location.protocol property. As a result, this function will be able to detect the correct protocol in the vast majority of cases.
If you log the location.protocol property to the browser’s console, you will get a better idea of what it contains:
//Dump out the location.protocol property //to the browser console. console.log(document.location.protocol);
For example, on a “plaintext” HTML page, this will result in the following: “http:”
This might come in useful if you need to dynamically create HTTPS links.