Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking Internet Connection within Chrome/Chromium Plugin; Image loaded is Cached

I am trying to check whether there is an internet connection from within a chrome plugin. While there is API call available that suggests to do check that, it only checks if there is internet connection possible, theoretically. To get this information, I try to load an Image

checkConnection() {
    var newImg = new Image;
    newImg.src = url;
    newImg.onload = function() { ... }
    newImg.onerror = function() { ... }
}

I do use the Image object to avoid all these problems with Same-Origin-Policies that occur when using get request with JavaScript (I am using the code from within a plugin, so there is no address that has the same origin as my code :/ ). In principle, my code from above works. I have a setTimeout that calls checkConnection every other time. However, when the image was loaded successfully once (per plugin reload) it is stored in the cache and is loaded from there when the connection fails.

Do you have an idea how to bypass this problem? Or do you know of a smart way to check the internet connection from within a Chrome plugin without setting up a server that might tolerate the origin of my request?

like image 778
jan_w Avatar asked Nov 28 '25 22:11

jan_w


1 Answers

You have 3 options that I know of...

Checking the internet connection

After some quick Googling I found navigator.onLine. It looks like you can use this to check internet connectivity, but it is not always entirely accurate.

Stopping the image from caching

If you have control of the domain where the image is hosted you can set headers telling the browser not to cache the image.

Cache-Control: no-cache, must-revalidate // HTTP/1.1
Expires: Sat, 26 Jul 1997 05:00:00 GMT // Date in the past

If you do NOT have control of the domain, when loading the image try appending a GET variable to the URL with a random number or the current timestamp.

E.g.

https://example.com/image.png?time=1496222683
https://example.com/image.png?time=1496223323
https://example.com/image.png?time=1496222313

This can trick the browser into thinking you are requesting a new resource.

like image 163
Tom Wright Avatar answered Nov 30 '25 12:11

Tom Wright



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!