How do I check if a webpage is on HTTP and if so, switch to HTTPS in JavaScript?

879 Views Asked by At

I am trying to test if a webpage is HTTP and then if so, I want it to go to the HTTPS version of the site. However, it is not working. For some reason, no error message is thrown, but it doesn't execute. The javascript is on domain1.com and the webpage is on domain2.com

domain1.com/sec/sec.js:

function sec(){
var loc = window.location.href;
loc.replace("http", "https");
for(window.location.href; window.location.href != loc;){
window.location = loc;
}
}

domain2.com/index.html

<html>
<head> 
<title></title> 
<script src = "domain1.com/sec/sec.js"></script> 
<script>sec();</script> 
</head> 
</html> 

Anyone have any working code snippets? Thank you!

3

There are 3 best solutions below

0
Islam Alshiki On BEST ANSWER

I think this will help you.

function Check(){
  return location.protocol === 'https:'
}
if ( !Check()){
  var _location = location.toString();
  var _newLink = _location.replace('http:', 'https:');
  location = _newLink ;
}
1
hari_048 On

You cannot convert to https this simple. What you are doing is client side scripting. Http and all related stuffs are done on the server side. And changing from http to https is not that simple. You have to get a signed certificate from an authorized person. Applying the certificates is done in server side though

0
broofa On

Use the location.protocol property to read/write just the http/https portion of the current URL. For example:

function sec() {
  if (location.protocol === 'http:') {
    location.protocol = 'https:';
  }
}