Detect HTTPS with JavaScript [duplicate]

一笑奈何 提交于 2019-12-29 04:27:34

问题


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?


回答1:


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");



回答2:


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.




回答3:


location.protocol works on all browsers.




回答4:


How about this ?

 var protocol = window.location.href.indexOf("https://")==0?"https":"http";



回答5:


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/




回答6:


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.



来源:https://stackoverflow.com/questions/2855529/detect-https-with-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!