This repository has been archived by the owner on Mar 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chrome-mock.js
91 lines (83 loc) · 2.45 KB
/
chrome-mock.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const jsdom = require('jsdom');
const { JSDOM } = jsdom;
class ChromeMock {
constructor() {
this.reset = this.reset.bind(this);
this.reset();
}
createBrowserAction(options) {
const browserAction = {
window: (new JSDOM('', { runScripts: 'dangerously' })).window
};
this.browserAction = browserAction;
this.browserAction.window.chrome = {
tabs: {
query: this.onBrowserActionTabsQuery.bind(this),
sendMessage: this.onRuntimeSendMessage.bind(this, null)
}
};
if (options.script) {
const script = this.browserAction.window.document.createElement('script');
script.innerHTML = options.script;
this.browserAction.window.document.body.appendChild(script);
}
return this.browserAction;
}
createTab(options) {
const html = options.html || '';
const tabId = this.tabs.length;
const tab = {
id: tabId,
tabId: tabId,
window: (new JSDOM(html, { runScripts: 'dangerously' })).window,
__onRuntimeMessageListeners: []
};
this.tabs.push(tab);
this.tabs[tabId].window.chrome = {
runtime: {
onMessage: this.addRuntimeMessageListener.bind(this, tabId),
sendMessage: this.onRuntimeSendMessage.bind(this, tabId)
}
};
if (options.content_scripts) {
options.content_scripts.forEach(cs => {
const script = this.tabs[tabId].window.document.createElement('script');
script.innerHTML = cs;
this.tabs[tabId].window.document.body.appendChild(script);
});
}
return this.tabs[tabId];
}
addRuntimeMessageListener(tabId, callback) {
if (this.tabs[tabId]) {
this.tabs[tabId].__onRuntimeMessageListeners.push(callback);
}
}
onBrowserActionTabsQuery(options, sendResponse) {
sendResponse(this.tabs.map(tab => ({ id: tab.id })));
}
onRuntimeSendMessage(senderTabId, tabId, message, sendResponse) {
const sender = {
tab: {
id: senderTabId
}
}
if (typeof tabId === 'number') {
if (this.tabs[tabId]) {
this.tabs[tabId].__onRuntimeMessageListeners.forEach(listener => listener(message, sender, sendResponse));
}
} else {
// Call all tabs
this.tabs.forEach(tab => {
tab.__onRuntimeMessageListeners.forEach(listener => {
listener(message, sender, sendResponse)
});
});
}
}
reset() {
this.browserAction = null;
this.tabs = [];
}
}
module.exports = new ChromeMock();