How to load images from the web in electron


#1

Hello,

For whatever reason, I keep getting a net::ERR_CONNECTION_REFUSED error whenever I try to create an img element in a renderer process. For example, If I run the following command in the devtools console:

> var img = document.createElement('img')
> img.src = 'http://i.imgur.com/nsw1Ga6.jpg'

I get the following error message:
GET http://i.imgur.com/nsw1Ga6.jpg net::ERR_CONNECTION_REFUSED

But if I were to load a local image:
> img.src = 'file://absolute/path/to/some/img.jpg' or
> img.src = '../relative/path/to/some/img.jpg'
I get no such error.

What confuses me is that I have no problems making an external http request. In theory I could GET the image from the web, save it locally, then pass the local address into img.src. This can’t be the only way though. What stupidly simple option/setting am I missing here? Any ideas?

Thanks in advance for you help.


#2

Are you connecting through a proxy or something else that might alter HTTP requests? I tried locally and I am able to load the image using your first two commands.


#3

Hi John,

Thanks for such a quick reply, you nudged me in the right direction. I think I found the source of the problem. I took another look at my main process and I saw an unfamiliar line in there:

app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1');

Once I removed this line, I no longer got the error. For those that might stumble upon this thread in the future, this line adds a command line option to chromium that forces all hostnames to be mapped to 127.0.0.1. So when I requested an image like http://imgur.com/whatever.jpg, chromium looked for it in http://127.0.0.1/whatever.jpg. And since I have no local servers running, chromium threw the net::ERR_CONNECTION_REFUSED. At least I think that’s how it works. To be honest I can’t remember when or why I added this. Might have been when I first downloaded electron and was playing around with the provided methods.

Thanks to john for saving my day.