Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML/JavaScript - Remote img src with automatic http/https prefix

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).

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="(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.

Could also use base64 to bypass the HTTP/HTTPS problem altogether, but this isn't ideal for what I'm doing.

What can you guys recommend?

like image 982
Pavel Avatar asked May 26 '12 07:05

Pavel


1 Answers

Just do :

<img src="//remotehost/path/to/a.png" alt="Image A" />
like image 129
xdazz Avatar answered Nov 15 '22 19:11

xdazz