Detect HTTP or HTTPS then force HTTPS in JavaScript

Detect HTTP or HTTPS then force HTTPS in JavaScript

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:”;


Solution 1:

Try this

if (location.protocol != 'https:')
 location.href = 'https:' + window.location.href.substring(window.location.protocol.length);

Solution 2:

Setting location.protocol navigates to a new URL. No need to parse/slice anything.

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

Firefox 49 has a bug where https works but https: does not. Said to be fixed in Firefox 54.

Solution 3:

It is not good idea because you just temporary redirect user to https and browser doesn’t save this redirect.

You describe task for web-server (apache, nginx etc) http 301, http 302

Related:  Getting an absolute URL from a relative one. (IE6 issue)

Solution 4:

How about this?

if (window.location.protocol !== 'https:') {
    window.location = 'https://' + window.location.hostname + window.location.pathname + window.location.hash;

Ideally you’d do it on the server side, though.

Solution 5:

if (location.protocol == 'http:')
  location.href = location.href.replace(/^http:/, 'https:')

Solution 6:

Not a Javascript way to answer this but if you use CloudFlare you can write page rules that redirect the user much faster to HTTPS and it’s free. Looks like this in CloudFlare’s Page Rules:

enter image description here