-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
63 lines (54 loc) · 2.18 KB
/
background.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
'use strict';
console.log("Background script running");
// Event to run execute.js content when extension's button is clicked
chrome.action.onClicked.addListener(execScript);
chrome.runtime.onConnect.addListener((port) => {
console.assert(port.name == "changeCSS");
port.onMessage.addListener((request) => {
if (request.action === 'changeCSS') {
const { previousCssFile, cssFile, selectedOption } = request;
console.log("previousCssFile: " + previousCssFile);
console.log("cssFile: " + cssFile);
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const tabId = tabs[0].id;
if (previousCssFile !== 'styles/none.css') {
chrome.scripting.removeCSS({
target: { tabId },
files: [previousCssFile]
}, () => {
if (chrome.runtime.lastError) {
port.postMessage({ success: false, error: chrome.runtime.lastError.message });
return;
}
});
}
if (cssFile !== 'styles/none.css') {
chrome.scripting.insertCSS({
target: { tabId },
files: [cssFile]
}, () => {
if (chrome.runtime.lastError) {
port.postMessage({ success: false, error: chrome.runtime.lastError.message });
} else {
port.postMessage({ success: true, selectedOption: selectedOption });
}
});
}
});
}
});
});
async function getActiveTabId() {
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
return (tabs.length > 0) ? tabs[0].id : null;
}
async function execScript() {
const tabId = await getActiveTabId();
if (!tabId) return;
chrome.scripting.executeScript({
target: { tabId },
files: ["contentScript.js"]
}, function () {
console.log("Content script loaded.");
});
}