Skip to content

Instantly share code, notes, and snippets.

@andreasvirkus
Last active April 29, 2020 21:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreasvirkus/c9f91ddb201fc78042bf7d814af47121 to your computer and use it in GitHub Desktop.
Save andreasvirkus/c9f91ddb201fc78042bf7d814af47121 to your computer and use it in GitHub Desktop.

Extension reloader

This will watch a Chrome extension's file directory, compile a hash based on the file names and date and reload the extension/add-on when the directory undergoes changes.

Compatible with Webpack and any other type of build setup! 📦

Usage

Add the script to your extension's manifest.json

"background": ["reloader.js", "background.js"]

You're all set!

Disclaimer

Currently doesn't work in Firefox because of a WON'T FIX for the getPackageDirectoryEntry method 😕 (in their own words, Firefox add-ons do not have a directory - smh)

Disclaimer #2: Mozilla's web-ext run seems like a better tool for this 💯

/* global chrome */
// Inspired by crx-hotreload package
// https://github.com/xpl/crx-hotreload/blob/master/hot-reload.js
const filesInDirectory = dir => new Promise(resolve =>
dir.createReader().readEntries(entries =>
Promise.all(entries.filter(e => e.name[0] !== '.').map(e =>
e.isDirectory
? filesInDirectory(e)
: new Promise(resolve => e.file(resolve))
))
.then(files => [].concat(...files))
.then(resolve)
)
)
const timestampForFilesInDirectory = dir => filesInDirectory(dir)
.then(files => files.map(f => f.name + f.lastModifiedDate).join())
const watchChanges = (dir, lastTimestamp) => {
timestampForFilesInDirectory(dir).then(timestamp => {
if (!lastTimestamp || (lastTimestamp === timestamp)) {
setTimeout(() => watchChanges(dir, timestamp), 1000)
} else {
console.log('%c 🚀 Reloading Extension', 'color: #FF00FF')
chrome.runtime.reload()
}
})
}
// Init if in dev environment
chrome.management.getSelf(self => {
if (self.installType === 'development' &&
'getPackageDirectoryEntry' in chrome.runtime
) {
console.log('%c 📦 Watching for file changes', 'color: #FF00FF')
chrome.runtime.getPackageDirectoryEntry(dir => watchChanges(dir))
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment