-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground-script.js
67 lines (58 loc) · 1.44 KB
/
background-script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const { name } = chrome.runtime.getManifest()
// Create the connection.
const socket = new WebSocket('ws://localhost:1337')
// Let the webpack plugin know that we're connected.
// We do this with a message instead of listening on connection
// because we only want it to know with this connection.
socket.onopen = event => {
console.log(name + ' will auto reload')
socket.send(
JSON.stringify(
{
type: 'RELOADED',
payload: name
}
)
)
}
// When the plugin stops so does the server, but we need
// to know when it starts back up. So we listen for a new
// connection with an interval and then reload the runtime.
socket.onclose = event => {
const reconnecter = setInterval(() => {
try {
const socket = new WebSocket('ws://localhost:1337')
socket.onopen = event => {
clearInterval(reconnecter)
reloadAll()
}
} catch (error) {}
}, 2000)
}
// Listen on messages.
socket.onmessage = event => {
const { data } = event
switch (data) {
case 'RELOAD_EXTENSION':
reloadExtension()
break
case 'RELOAD_ALL':
reloadAll()
break
}
}
/**
* Reloads the extension.
*/
function reloadExtension() {
chrome.runtime.reload()
}
/**
* Reloads all tabs with the extension running.
*/
function reloadAll() {
chrome.tabs.query({}, tabs => {
tabs.forEach(tab => chrome.tabs.sendMessage(tab.id, { type: 'RELOAD' }))
reloadExtension()
})
}