-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
67 lines (56 loc) · 1.91 KB
/
background.js
File metadata and controls
67 lines (56 loc) · 1.91 KB
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
// Copyright (c) 2019 SafetyCulture Pty Ltd. All Rights Reserved.
// Map of Panel connections. The 'tabId' is used as key.
// There are two connections/ports for every tabId
// 1) Port to the panel script
// 2) Port to the content script
//
// Example:
// connections[1].panel => pane port
// connections[1].content => content port
/* global chrome */
let connections = {};
// eslint-disable-next-line no-undef
chrome.runtime.onConnect.addListener(port => {
if (port.name !== "panel" && port.name !== "content") {
return;
}
let extensionListener = message => {
const tabId = port.sender?.tab?.id >= 0 ? port.sender.tab.id : message.tabId;
// The original connection event doesn't include the tab ID of the
// DevTools page, so we need to send it explicitly (attached
// to the 'init' event).
if (message.action === "init") {
if (!connections[tabId]) {
connections[tabId] = {};
}
connections[tabId][port.name] = port;
return;
}
// Other messages are relayed to specified target if any
// and if the connection exists.
if (message.target) {
const conn = connections[tabId][message.target];
if (conn) {
conn.postMessage(message);
}
}
};
// Listen to messages sent from the panel script.
port.onMessage.addListener(extensionListener);
// Remove panel connection on disconnect.
port.onDisconnect.addListener(function (port) {
port.onMessage.removeListener(extensionListener);
const tabs = Object.keys(connections);
for (let i = 0, len = tabs.length; i < len; i++) {
if (connections[tabs[i]][port.name] === port) {
delete connections[tabs[i]][port.name];
// If there is not port associated to the tab, remove it
// from the connections map.
if (Object.keys(connections[tabs[i]]).length === 0) {
delete connections[tabs[i]];
}
break;
}
}
});
});