I am trying to find how can I detect with JavaScript if I am in a HTTP or HTTPS environment.
I am calling an Ajax request so if I am in HTTPS and call HTTP Ajax then I get a 302 Moved Temporarily.
I was thinking of getting the current window.location.href
and do a string manipulation.
What is the best way of detecting HTTPS using JavaScript?
Looking at how google analytics add their script to the page:
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
Then document.location.protocol would seem safe for all browsers.
You can use the non-standard
window.location.protocol
In Firefox: MDC documentation
In IE, it seems to be
document.location.protocol
MSDN documentation
I can't find reliable info on how this behaves on other browsers, but I expect they adhere to the quasi-standard of document.location.protocol
.
Maybe the jQuery url plugin sorts this out without having to deal with cross-browser differences - I've never used it myself, but it looks promising:
jQuery.url.attr("protocol");
location.protocol
works on all browsers.
How about this ?
var protocol = window.location.href.indexOf("https://")==0?"https":"http";
In many instances, one can omit the protocol altogether. So, instead of
<img src="https://test.com/image.jpg" />
one could use
<img src="//test.com/image.jpg" />
The browser then adds the current protocol automatically. This also works for including files in the head, and it should also work for ajax calls.
Edit: Doing this is now considered to be an anti-pattern:
Now that SSL is encouraged for everyone and doesn’t have performance concerns, this technique is now an anti-pattern. If the asset you need is available on SSL, then always use the https:// asset.
Allowing the snippet to request over HTTP opens the door for attacks like the recent Github Man-on-the-side attack. It’s always safe to request HTTPS assets even if your site is on HTTP, however the reverse is not true.
see: http://www.paulirish.com/2010/the-protocol-relative-url/
There's a really neat lib called URI for things like this. https://github.com/medialize/URI.js
You probably don't need this just to grab the protocol, but if you're going to be string manipulating URIs, you should use this.
精彩评论