HTML/JavaScript - 带有自动 http/https 前缀的远程 img src
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10764460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML/JavaScript - Remote img src with automatic http/https prefix
提问by Pavel
Displaying an image from a remote server:
显示来自远程服务器的图像:
<img src="http://remotehost/path/to/a.png" alt="Image A" />
However, if the current page is accessed via HTTPS, linking images via unencrypted HTTP will yield security warnings. While I could just specify https:// regardless of the current protocol, doing so would be wasteful since I really don't care to secure the transmission of this image unless it is necessary (when the visitor is using HTTPS).
但是,如果当前页面是通过 HTTPS 访问的,则通过未加密的 HTTP 链接图像将产生安全警告。虽然我可以只指定 https:// 而不管当前协议,这样做会很浪费,因为我真的不关心保护这个图像的传输,除非有必要(当访问者使用 HTTPS 时)。
Is it possible to specify a URL for the src attribute of the img tag such that the protocol in the URL is dynamically chosen based on the protocol used to access the current page? To illustrate what I mean:
是否可以为 img 标签的 src 属性指定一个 URL,以便根据用于访问当前页面的协议动态选择 URL 中的协议?为了说明我的意思:
<img src="(JavaScript's window.location.protocol)//remotehost/path/to/a.png" alt="Image A" />
What if we use JavaScript? We could give the img tag an id so that we can locate it and set the src to start with window.location.protocol.
如果我们使用 JavaScript 呢?我们可以给 img 标签一个 id,以便我们可以定位它并将 src 设置为以 window.location.protocol 开头。
Could also use base64 to bypass the HTTP/HTTPS problem altogether, but this isn't ideal for what I'm doing.
也可以使用 base64 完全绕过 HTTP/HTTPS 问题,但这对我正在做的事情来说并不理想。
What can you guys recommend?
大家有什么可以推荐的吗?
回答by xdazz
Just do :
做就是了 :
<img src="//remotehost/path/to/a.png" alt="Image A" />
回答by s1i2v3a
if the file is on LAN you need to use file:// protocol
add 5 slash before path
so my server name is athensserver
so f://///athensserver/
(anything you shared here)
如果文件在 LAN 上,则需要使用 file:// 协议在路径前添加 5 个斜杠,这样我的服务器名称就是athensserver
这样f://///athensserver/
(您在此处共享的任何内容)
file://///athensserver/athens/0/e1.png"