Created
September 16, 2020 08:07
-
-
Save iamspark1e/4b483ee48e8eb72d92b8f38803e68752 to your computer and use it in GitHub Desktop.
Enable hot reload for Chrome Extension in Dev Mode.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 reload = () => { | |
chrome.tabs.query({ | |
active: true, | |
currentWindow: true | |
}, tabs => { // NB: see https://github.com/xpl/crx-hotreload/issues/5 | |
if (tabs[0]) { | |
chrome.tabs.reload(tabs[0].id) | |
} | |
chrome.runtime.reload() | |
}) | |
} | |
const watchChanges = (dir, lastTimestamp) => { | |
timestampForFilesInDirectory(dir).then(timestamp => { | |
if (!lastTimestamp || (lastTimestamp === timestamp)) { | |
setTimeout(() => watchChanges(dir, timestamp), 1000) // retry after 1s | |
} else { | |
reload() | |
} | |
}) | |
} | |
chrome.management.getSelf(self => { | |
if (self.installType === 'development') { | |
chrome.runtime.getPackageDirectoryEntry(dir => watchChanges(dir)) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment