Skip to content

Commit 04c01e8

Browse files
author
hoang.tran12
committed
fix logic run background scripts
1 parent fafa5de commit 04c01e8

File tree

4 files changed

+111
-77
lines changed

4 files changed

+111
-77
lines changed

empty_script.js

Lines changed: 29 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -109,48 +109,49 @@ export default {
109109
// - can use chrome extension APIs
110110
// - CANNOT use dynamic imports, but can use GLOBAL variables in background_script.js
111111
// - can use UfsGlobal
112+
// - context => background context => can access GLOBAL in background_script.js
112113
backgroundScript: {
113-
onDocumentStart: (details) => {},
114-
onDocumentIdle: (details) => {},
115-
onDocumentEnd: (details) => {},
114+
onDocumentStart: (details, context) => {},
115+
onDocumentIdle: (details, context) => {},
116+
onDocumentEnd: (details, context) => {},
116117

117118
// advanced
118119
runtime: {
119-
onInstalled: () => {},
120-
onStartup: () => {},
121-
onMessage: ({ request, sender, sendResponse }) => {},
120+
onInstalled: (reason, context) => {},
121+
onStartup: (nil, context) => {},
122+
onMessage: ({ request, sender, sendResponse }, context) => {},
122123
},
123124
webNavigation: {
124-
onCreatedNavigationTarget: (details) => {},
125-
onHistoryStateUpdated: (details) => {},
126-
onBeforeNavigate: (details) => {},
125+
onCreatedNavigationTarget: (details, context) => {},
126+
onHistoryStateUpdated: (details, context) => {},
127+
onBeforeNavigate: (details, context) => {},
127128
},
128129
webRequest: {
129130
// Can only modify requestHeaders (onBeforeSendHeaders) AND responseHeaders (onHeadersReceived)
130131
// Don't use async await for these two events if you want to return modified values
131-
onBeforeRedirect: (details) => {},
132-
onBeforeRequest: (details) => {},
133-
onBeforeSendHeaders: (details) => {},
134-
onCompleted: (details) => {},
135-
onErrorOccurred: (details) => {},
136-
onHeadersReceived: (details) => {},
137-
onResponseStarted: (details) => {},
138-
onSendHeaders: (details) => {},
132+
onBeforeRedirect: (details, context) => {},
133+
onBeforeRequest: (details, context) => {},
134+
onBeforeSendHeaders: (details, context) => {},
135+
onCompleted: (details, context) => {},
136+
onErrorOccurred: (details, context) => {},
137+
onHeadersReceived: (details, context) => {},
138+
onResponseStarted: (details, context) => {},
139+
onSendHeaders: (details, context) => {},
139140
},
140141
tabs: {
141-
onActivated: (details) => {},
142-
onAttached: (details) => {},
143-
onCreated: (details) => {},
144-
onDetached: (details) => {},
145-
onHighlighted: (details) => {},
146-
onMoved: (details) => {},
147-
onRemoved: (details) => {},
148-
onReplaced: (details) => {},
149-
onUpdated: (details) => {},
150-
onZoomChange: (details) => {},
142+
onActivated: (details, context) => {},
143+
onAttached: (details, context) => {},
144+
onCreated: (details, context) => {},
145+
onDetached: (details, context) => {},
146+
onHighlighted: (details, context) => {},
147+
onMoved: (details, context) => {},
148+
onRemoved: (details, context) => {},
149+
onReplaced: (details, context) => {},
150+
onUpdated: (details, context) => {},
151+
onZoomChange: (details, context) => {},
151152
},
152153
storage: {
153-
onChanged: (details) => {},
154+
onChanged: (details, context) => {},
154155
},
155156
},
156157
};

popup/helpers/utils.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,12 @@ function hasChildFunction(object, excludedNamesSet = new Set()) {
2525
}
2626

2727
export const canAutoRun = (script) => {
28-
let excludedNamesSet = new Set(["onClick", "onInstalled", "onStartup"]);
28+
let excludedNamesSet = new Set([
29+
"onClick",
30+
"onInstalled",
31+
"onStartup",
32+
"contextMenus",
33+
]);
2934
for (let context of CONTEXTS) {
3035
if (hasChildFunction(script[context], excludedNamesSet)) return true;
3136
}

scripts/background-scripts/background_script.js

Lines changed: 34 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import "../content-scripts/ufs_global.js"; // https://stackoverflow.com/a/628060
55
console.log(UfsGlobal);
66

77
const {
8-
runScriptInCurrentTab,
98
convertBlobToBase64,
109
getAllActiveScriptIds,
1110
trackEvent,
@@ -25,6 +24,9 @@ const GLOBAL = {
2524
trackEvent,
2625
fetch: customFetch,
2726
getCached,
27+
runScriptsTab,
28+
runScriptsBackground,
29+
checkWillRun,
2830
};
2931

3032
function getCached() {
@@ -90,15 +92,30 @@ function getDetailIds(details) {
9092
};
9193
}
9294

93-
function runScripts(eventChain, details, data) {
95+
function runScriptsBackground(
96+
eventChain,
97+
details,
98+
data,
99+
runAllScripts = false
100+
) {
94101
let allResponse;
95-
for (let scriptId of CACHED.activeScriptIds) {
102+
let scriptIds = runAllScripts
103+
? Object.keys(allScripts)
104+
: CACHED.activeScriptIds;
105+
106+
for (let scriptId of scriptIds) {
96107
const fn = checkWillRun(scriptId, "backgroundScript", eventChain, details);
97108
if (fn) {
98-
let res = fn(data ?? details);
99-
if (res) {
100-
if (!allResponse) allResponse = {};
101-
allResponse[scriptId] = res;
109+
try {
110+
// inject background context (GLOBAL) to func
111+
let res = fn(data ?? details, GLOBAL);
112+
console.log("runScriptsBackground", scriptId, eventChain, res);
113+
if (res) {
114+
if (!allResponse) allResponse = {};
115+
allResponse[scriptId] = res;
116+
}
117+
} catch (e) {
118+
console.log("runScriptsBackground ERROR", scriptId, eventChain, e);
102119
}
103120
}
104121
}
@@ -212,7 +229,7 @@ function listenWebRequest() {
212229
if (details.initiator?.startsWith("chrome-extension://")) return;
213230

214231
// console.log("details ne", rqEvent, details);
215-
let allData = runScripts(eventChain, details);
232+
let allData = runScriptsBackground(eventChain, details);
216233

217234
let modifiedDetails = {
218235
...details,
@@ -275,7 +292,7 @@ function listenNavigation() {
275292
}
276293
runScriptsTab(eventChain, MAIN, details);
277294
runScriptsTab(eventChain, ISOLATED, details);
278-
runScripts(eventChain, details);
295+
runScriptsBackground(eventChain, details);
279296
} catch (e) {
280297
console.log("ERROR:", e);
281298
}
@@ -297,7 +314,7 @@ function listenTabs() {
297314
// "onZoomChange",
298315
].forEach((event) => {
299316
chrome.tabs[event].addListener((details) => {
300-
runScripts("tabs." + event, details);
317+
runScriptsBackground("tabs." + event, details);
301318
});
302319
});
303320
}
@@ -318,7 +335,7 @@ function listenMessage() {
318335
sended = true;
319336
sendResponse(data);
320337
};
321-
runScripts(
338+
runScriptsBackground(
322339
"runtime.onMessage",
323340
null,
324341
// {
@@ -340,7 +357,7 @@ function main() {
340357
// listen change active scripts
341358
cacheActiveScriptIds();
342359
chrome.storage.onChanged.addListener((changes, areaName) => {
343-
runScripts("storage.onChanged", null, { changes, areaName });
360+
runScriptsBackground("storage.onChanged", null, { changes, areaName });
344361

345362
// areaName = "local" / "sync" / "managed" / "session" ...
346363
if (changes?.[listActiveScriptsKey]) cacheActiveScriptIds();
@@ -352,53 +369,22 @@ function main() {
352369
listenMessage();
353370

354371
chrome.contextMenus.onClicked.addListener(async (info) => {
355-
console.log(info);
356-
if (info.menuItemId == "ufs-magnify-image") {
357-
trackEvent("magnify-image-CONTEXT-MENU");
358-
/*
359-
{
360-
"editable": false,
361-
"frameId": 2491,
362-
"frameUrl": "https://www.deviantart.com/_nsfgfb/?realEstateId=166926a9-15ab-458d-b424-4385d5c9acde&theme=dark&biClientId=fdb7b474-671d-686c-7ebc-7027eecd49f0&biClientIdSigned=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJiaUNsaWVudElkIjoiZmRiN2I0NzQtNjcxZC02ODZjLTdlYmMtNzAyN2VlY2Q0OWYwIiwidHMiOjE3MTM0NjgyNTAsInVzZXJVdWlkIjoiZmRiN2I0NzQtNjcxZC02ODZjLTdlYmMtNzAyN2VlY2Q0OWYwIn0.z98X9tXSYMaUubtwGGG08NsikaoZ7iODsn_aWaeiGD0&newApi=2&platform=desktop",
363-
"linkUrl": "https://www.deviantart.com/join?referer=https%3A%2F%2Fwww.deviantart.com%2Fdreamup%3Fda_dealer_footer=1",
364-
"mediaType": "image",
365-
"menuItemId": "ufs-magnify-image",
366-
"pageUrl": "https://www.deviantart.com/kat-zaphire/art/Deep-in-the-forest-989494503",
367-
"srcUrl": "https://wixmp-70a14ff54af6225c7974eec7.wixmp.com/offers-assets/94f22a36-bb47-4836-8bce-fea45f844aa4.gif"
368-
} */
369-
let tab = await utils.getCurrentTab();
370-
utils.runScriptInTabWithEventChain({
371-
target: {
372-
tabId: tab.id,
373-
frameIds: [0],
374-
},
375-
scriptIds: ["magnify_image"],
376-
eventChain: "contentScript._createPreview",
377-
details: info,
378-
world: "ISOLATED",
379-
});
380-
}
372+
runScriptsBackground("contextMenus.onClicked", null, info, true);
381373
});
382374

383375
chrome.runtime.onStartup.addListener(async function () {
384-
runScripts("runtime.onStartup");
376+
runScriptsBackground("runtime.onStartup", null, null, true);
385377
});
386378

387379
chrome.runtime.onInstalled.addListener(async function (reason) {
388380
if (utils.hasUserId()) {
389-
await GLOBAL.trackEvent("ufs-RE-INSTALLED");
381+
await trackEvent("ufs-RE-INSTALLED");
390382
}
391383
// create new unique id and save it
392384
await setUserId();
393-
GLOBAL.trackEvent("ufs-INSTALLED");
394-
395-
chrome.contextMenus.create({
396-
title: "Magnify this image",
397-
contexts: ["image"],
398-
id: "ufs-magnify-image",
399-
});
385+
trackEvent("ufs-INSTALLED");
400386

401-
runScripts("runtime.onInstalled", null, reason);
387+
runScriptsBackground("runtime.onInstalled", null, reason, true);
402388
});
403389

404390
chrome.action.setBadgeBackgroundColor({ color: "#666" });

scripts/magnify_image.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,48 @@ export default {
7676
});
7777
},
7878
},
79+
80+
backgroundScript: {
81+
runtime: {
82+
onInstalled: () => {
83+
chrome.contextMenus.create({
84+
title: "Magnify this image",
85+
contexts: ["image"],
86+
id: "ufs-magnify-image",
87+
});
88+
},
89+
},
90+
contextMenus: {
91+
onClicked: (info, context) => {
92+
context.utils.trackEvent("magnify-image-CONTEXT-MENU");
93+
/*
94+
{
95+
"editable": false,
96+
"frameId": 2491,
97+
"frameUrl": "https://www.deviantart.com/_nsfgfb/?realEstateId=166926a9-15ab-458d-b424-4385d5c9acde&theme=dark&biClientId=fdb7b474-671d-686c-7ebc-7027eecd49f0&biClientIdSigned=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJiaUNsaWVudElkIjoiZmRiN2I0NzQtNjcxZC02ODZjLTdlYmMtNzAyN2VlY2Q0OWYwIiwidHMiOjE3MTM0NjgyNTAsInVzZXJVdWlkIjoiZmRiN2I0NzQtNjcxZC02ODZjLTdlYmMtNzAyN2VlY2Q0OWYwIn0.z98X9tXSYMaUubtwGGG08NsikaoZ7iODsn_aWaeiGD0&newApi=2&platform=desktop",
98+
"linkUrl": "https://www.deviantart.com/join?referer=https%3A%2F%2Fwww.deviantart.com%2Fdreamup%3Fda_dealer_footer=1",
99+
"mediaType": "image",
100+
"menuItemId": "ufs-magnify-image",
101+
"pageUrl": "https://www.deviantart.com/kat-zaphire/art/Deep-in-the-forest-989494503",
102+
"srcUrl": "https://wixmp-70a14ff54af6225c7974eec7.wixmp.com/offers-assets/94f22a36-bb47-4836-8bce-fea45f844aa4.gif"
103+
} */
104+
if (info.menuItemId == "ufs-magnify-image") {
105+
context.utils.getCurrentTab().then((tab) => {
106+
context.utils.runScriptInTabWithEventChain({
107+
target: {
108+
tabId: tab.id,
109+
frameIds: [0],
110+
},
111+
scriptIds: ["magnify_image"],
112+
eventChain: "contentScript._createPreview",
113+
details: info,
114+
world: "ISOLATED",
115+
});
116+
});
117+
}
118+
},
119+
},
120+
},
79121
};
80122

81123
function injectCss() {

0 commit comments

Comments
 (0)