Nat*_*n H 77 html javascript css https
我正在向页眉和页脚添加外部CSS文件和外部JS文件.加载HTTPS页面时,某些浏览器会抱怨我正在加载不安全的内容.
当页面本身是HTTPS时,是否有一种简单的方法可以让浏览器通过HTTPS加载外部内容?
Bal*_*usC 123
使用协议相对路径.
因此没有
<link rel="stylesheet" href="http://example.com/style.css">
<script src="http://example.com/script.js"></script>
Run Code Online (Sandbox Code Playgroud)
但是这样
<link rel="stylesheet" href="//example.com/style.css">
<script src="//example.com/script.js"></script>
Run Code Online (Sandbox Code Playgroud)
然后它将使用父页面的协议.
努力和詹姆斯韦斯特盖特在回答后来的答案时是正确的.
如果我们看看miscelanous行业级外部javascript包含,成功的使用document.location.protocol嗅探和脚本元素注入tu使用适当的协议.
所以你可以使用类似的东西:
<script type="text/javascript">
var protocol = (
("https:" == document.location.protocol)
? "https"
: "http"
);
document.write(
unescape(
"%3Cscript"
+ " src='"
+ protocol
+ "://"
+ "your.domain.tld"
+ "/your/script.js"
+ "'"
+ " type='text/javascript'
+ "%3E"
+ "%3C/script%3E"
) // this HAS to be escaped, otherwise it would
// close the actual (not injected) <script> element
);
</script>
Run Code Online (Sandbox Code Playgroud)
对于外部CSS包含也可以这样做.
顺便说一下:小心只在CSS中使用相对url()路径,如果有的话,否则你可能仍会得到"混合安全和不安全"的警告....