0

Like to load https version of a page if its available. My code is 'blocked by CORS policy'. Seems stupid that a secure connection should be blocked. Can I fix this with javascript only without having to add further serverside code? (and without using jquery).

// check if ssl version of the page is available
if (window.location.protocol=="http:") { 
 newurl = "https:"+window.location.href.substr(5);

 // get an ajax object
 if (window.XMLHttpRequest) req=new XMLHttpRequest();
 else if (window.ActiveXObject) req=new ActiveXObject("Microsoft.XMLHTTP");
 else req=false;
 
 // run ajax
 if (req) {
  // setup return function to load page if it was successful
  req.onreadystatechange=function() {
   if (req.readyState!=4) return;
   if (req.status==200) location.href=newurl;
  }
  // attempt to open url
  req.open("GET",newurl,true);
  req.send("");
 }
}
peeebeee
  • 2,541
  • 6
  • 21
  • 26
  • https://debugnotes.wordpress.com/2015/06/17/ajax-and-ssl/ – MuffinMan Feb 21 '20 at 07:30
  • https://stackoverflow.com/questions/41030425/disabling-cors-using-js-fetch – BadPiggie Feb 21 '20 at 07:31
  • New url to be `"https:"+ window.location.href.substr(6)` – Santhosh S Feb 21 '20 at 07:32
  • Apparently making a secured remote AJAX call from an unsecured context should be permissible, but in my testing only unsecure to unsecure, and secure to secure works. – user1416526 Feb 21 '20 at 09:19
  • @user1416526 - what value does your server respond with for the header: Access-Control-Allow-Origin? – MuffinMan Feb 21 '20 at 10:53
  • Access to XMLHttpRequest at 'https://siteB.com/' from origin 'http://siteA.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. GET https://siteB.com/ net::ERR_FAILED – user1416526 Mar 20 '20 at 04:29
  • Answer that worked for me was to add this to the website header: header('Access-Control-Allow-Origin: http://siteB.com'); // php – user1416526 Mar 20 '20 at 04:31

0 Answers0