0

I have been having some trouble using a javascript script that automatically makes you get forwarded to use ssl. example,

http://www.example.com/link becomes https://www.example.com/link

But my issue is that is continuously loads the script, but I want it to stop when it is already loaded. It reloads continuously, making it very annoying and hard to click the links on the page.

Here is my current script

window.location = "https://" + window.location.hostname + window.location.pathname + window.location.search;

golionz
  • 3
  • 1
  • possible duplicate of [How do I determine whether a page is secure via JavaScript?](http://stackoverflow.com/questions/414809/how-do-i-determine-whether-a-page-is-secure-via-javascript) – royhowie Dec 04 '14 at 17:57

1 Answers1

3

You need this:

if(window.location.protocol == 'http:') {
    window.location = "https://" + window.location.hostname + window.location.pathname + window.location.search;
}

...or even better:

if(window.location.protocol == 'http:') {
    window.location.replace(window.location.toString().replace(/^http:/, 'https:'));
}

Second variant is better because:

  • URL may be complex and will be handled properly
  • Because of using window.location.replace() instead of directly assigning a string to window.location, previous URL will be removed from history and when user clicks 'back' button, he will jump to original page, not to the one with "http:" protocol: http://www.w3schools.com/jsref/met_loc_replace.asp

But it's better to implement this on server side.

Andrew Dunai
  • 3,061
  • 19
  • 27