ElectronJS - Cache HTML and JS files from remote server

3.4k views Asked by At

I have an electron app that retrieves the app files (.html & .js) from a remote server using the function mainWindow.loadURL('http://www.example.com/index.html')

The problem arises if the users network connection to the internet is offline or disconnected.

Is there a way in electron to cache the html and js files so that if the user is offline, electron will automatically load from the cache.

I have tried to use the HTML5 Application Cache and a plugin for webpack https://github.com/NekR/offline-plugin but these do not seem to work.

2

There are 2 answers

1
Rod On

I see this is an old question but I stumbled across this when doing a semi-related search and there is no answer at all right now, so I'll provide one:


Ignoring the Electron-specific nature of this question, the web-standard way to do this is using Service Workers. Here are some docs on that:

I think this would be the most direct way to solve this, even within Electron. (An advantage of Electron here is that you have a single, known browser to make this work for, but I think what you are trying to do fits perfectly within the problem-space that Service Workers are designed to address.)


That said, I think Sayam's comment/question is valid -- if this html/js is the actual content of your electron app, and assuming it doesn't change too often you could (and maybe should) distribute it with the app itself. Then you don't need to do anything special for offline support (as long as that html/js doesn't need network-based resources), and changes to that code are deployed as application updates.

Personally I think that once-per-week is about the maximum frequency of updates for which this approach is suitable. It would not bother me if an app auto-updated 2 or 3 times per month, but I think I'd uninstall an app that updates itself 2 or 3 times per week if I had that option.


There may also be some electron and/or node modules that address this problem-space, but I've never bothered to look because one of the two options above has always seemed appropriate to me.

0
Scalway On

Old question but still valid usecase (offline cache for dynamic assets). here is article that describes one solution for that (own ExpressJS caching middleware). Author made npm library to address that.