Detect HTTP or HTTPS then force HTTPS in JavaScript

Registered User picture Registered User · Jan 18, 2011 · Viewed 261.8k times · Source

Is there any way to detect HTTP or HTTPS and then force usage of HTTPS with JavaScript?

I have some codes for detecting the HTTP or HTTPS but I can't force it to use https: .

I'm using the window.location.protocol property to set whatever the site is to https: then refresh the page to hopefully reload a new https'ed URL loaded into the browser.

if (window.location.protocol != "https:") {
   window.location.protocol = "https:";
   window.location.reload();
}

Answer

Soumya picture Soumya · Jan 18, 2011

Try this

if (location.protocol !== 'https:') {
    location.replace(`https:${location.href.substring(location.protocol.length)}`);
}

location.href = blah adds this redirect to the browser history. If the user hits the back button, they will be redirected back to the the same page. It is better to use location.replace as it doesn't add this redirect to the browser history.