Developing of a Chrome extension without reloads

While developing a Chrome extension one needs to repeatedly reload the extension itself on Extensions tab and to reload the page to new version of a content script of the extension to load.

It is several actions just to apply changes made to the code.

There are extensions to automate this, for example Dev extensions reload, but even with these extensions one need to do something, as far as i checked them. Because them do not watch files for changes.

But there is an easy hack to develop an extension without reloads at all, that would work in a lot of cases. We can just reread a script with code we develop and eval it, and in this way always use the latest version of the code.

Loading and executing the code

To be able to load the file we need to add something like this to manifest.json:

"web_accessible_resources": [
  "script.js"
]

Then we can load the file:

let scriptUrl = chrome.runtime.getURL('script.js')
fetch(
  scriptUrl
).then(function(res) {
  res.text().then(function(r) {
    let code = ''+r;
    eval(code)
    foo(bar)
  })
})

Here we get a special URL for our file and do the usual fetch and eval the code. foo is function from script.js, that will be always the latest version of foo.

Summary

So, with this approach one can separate (if it is possible) the code of an extension to several parts. A static part which could for example bind event listeners to the interesting events. And a dynamic part which will be reloaded by the static one just before executing code from it.

Of course in complex cases it can became inconvenient, but for a simple extension that for example do something when user clicks something or presses something it is perfect]

 

shitpoet@gmail.com

 

free hit counters