Skip to content

Commit

Permalink
Merge pull request #16 from HoangTran0410/dev
Browse files Browse the repository at this point in the history
Fix clickContentScript, onDocumentStart/Idle/End by correct world: MAIN/ISOLATED
  • Loading branch information
HoangTran0410 authored Apr 7, 2024
2 parents c2351b9 + 07aad60 commit ab1c790
Show file tree
Hide file tree
Showing 15 changed files with 112 additions and 174 deletions.
23 changes: 17 additions & 6 deletions manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,27 +29,38 @@
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["scripts/content-scripts/scripts/ufs_global_webpage_context.js"],
"js": ["scripts/content-scripts/content_script.js"],
"run_at": "document_start",
"world": "MAIN"
"world": "ISOLATED",
"match_origin_as_fallback": true,
"match_about_blank": true
},
{
"matches": ["<all_urls>"],
"js": ["scripts/content-scripts/document_start.js"],
"js": [
"scripts/content-scripts/scripts/ufs_global_webpage_context.js",
"scripts/content-scripts/run_scripts.js"
],
"run_at": "document_start",
"world": "ISOLATED"
"world": "MAIN",
"match_origin_as_fallback": true,
"match_about_blank": true
},
{
"matches": ["<all_urls>"],
"js": ["scripts/content-scripts/document_idle.js"],
"run_at": "document_idle",
"world": "ISOLATED"
"world": "MAIN",
"match_origin_as_fallback": true,
"match_about_blank": true
},
{
"matches": ["<all_urls>"],
"js": ["scripts/content-scripts/document_end.js"],
"run_at": "document_end",
"world": "ISOLATED"
"world": "MAIN",
"match_origin_as_fallback": true,
"match_about_blank": true
}
],
"web_accessible_resources": [
Expand Down
3 changes: 1 addition & 2 deletions popup/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,7 @@ function createTabs() {
// show scripts count
if (tab.showCount) {
let avaiCount = tab.scripts.filter((script) => !isTitle(script)).length;
let allCount = Object.keys(allScripts).length;
tabBtn.innerHTML += ` (${avaiCount}/${allCount})`;
tabBtn.innerHTML += ` (${avaiCount})`;
}

// custom style
Expand Down
10 changes: 5 additions & 5 deletions popup/tabs.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const tabs = [
{
...CATEGORY.search,
scripts: [
// s._test,
s._test,
s.search_userscript,
s.whatFont,
s.similarWeb,
Expand All @@ -49,10 +49,10 @@ const tabs = [
...CATEGORY.download,
scripts: [
createTitle("--- All in one ---", "--- Tổng hợp ---"),
s.savevideo_me,
s.vuiz_getLink,
s.saveAllVideo,
s.savevideo_me,
s.getLinkLuanxt,
s.vuiz_getLink,
// s.bookmark_exporter,
s.twitter_downloadButton,
createTitle("--- Music ---", "--- Nhạc ---"),
Expand Down Expand Up @@ -106,9 +106,9 @@ const tabs = [
s.fb_downloadCommentVideo,
s.fb_videoDownloader,
s.fb_getAvatarFromUid,
s.fb_storyInfo,
// s.fb_storyInfo,
createTitle("--- Bulk Download ---", "--- Tải hàng loạt ---"),
s.fb_bulkDownload,
// s.fb_bulkDownload,
s.fb_downloadAlbumMedia,
s.fb_downloadWallMediaFromPosts,
s.fb_getAllAlbumInformation,
Expand Down
58 changes: 58 additions & 0 deletions scripts/content-scripts/content_script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import("./scripts/ufs_global_webpage_context.js");

// communication between page-script and content-script
(() => {
function sendToPageScript(event, data) {
window.dispatchEvent(
new CustomEvent("ufs-contentscript-sendto-pagescript", {
detail: { event, data },
})
);
}
window.addEventListener("ufs-pagescript-sendto-contentscript", async (e) => {
let { event, data } = e.detail;
switch (event) {
case "getURL":
sendToPageScript(event, chrome.runtime.getURL(data));
break;
case "getActiveScripts":
const key = "activeScripts";
let ids = (await chrome.storage.sync.get([key]))?.[key] || "";
let path = chrome.runtime.getURL("/scripts/");
sendToPageScript(event, { ids, path });
break;
}
});
})();

// Run script on user click (if clicked script has onClickContentScript event)
(async () => {
try {
const { MsgType, ClickType } = await import("../helpers/constants.js");
const { isFunction } = await import("../helpers/utils.js");

chrome.runtime.onMessage.addListener(async function (
message,
sender,
sendResponse
) {
console.log("> Received message:", message);

switch (message.type) {
case MsgType.runScript:
let scriptId = message.scriptId;
const script = (
await import(chrome.runtime.getURL("/scripts/") + scriptId + ".js")
)?.default;

if (script && isFunction(script[ClickType.onClickContentScript])) {
script[ClickType.onClickContentScript]();
console.log("> Run script " + scriptId);
}
break;
}
});
} catch (e) {
console.log("ERROR: ", e);
}
})();
7 changes: 1 addition & 6 deletions scripts/content-scripts/document_end.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
(async () => {
let key = "activeScripts";
let ids = (await chrome.storage.sync.get([key]))?.[key] || "";
window.dispatchEvent(
new CustomEvent("ufs-run-page-scripts", {
detail: {
event: "onDocumentEnd",
ids: ids.split(","),
},
detail: { event: "onDocumentEnd" },
})
);
})();
7 changes: 1 addition & 6 deletions scripts/content-scripts/document_idle.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
(async () => {
let key = "activeScripts";
let ids = (await chrome.storage.sync.get([key]))?.[key] || "";
window.dispatchEvent(
new CustomEvent("ufs-run-page-scripts", {
detail: {
event: "onDocumentIdle",
ids: ids.split(","),
},
detail: { event: "onDocumentIdle" },
})
);
})();
102 changes: 0 additions & 102 deletions scripts/content-scripts/document_start.js

This file was deleted.

35 changes: 12 additions & 23 deletions scripts/content-scripts/run_scripts.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,36 +7,25 @@
// Kể cả việc nó đã được viết ở file khác (utils, helper, ...)
// Quá trình maintain sẽ khó hơn 1 chút, nhưng script sẽ chạy chính xác hơn

(() => {
// let search = new URLSearchParams(getCurrentScriptSrc().split("?")?.[1]);
// let path = search.get("path");

let { path, ids, event } = JSON.parse(
localStorage.getItem("ufs-auto-run-scripts") ?? "{}"
);
(async () => {
let ids = [],
path = "";

// run script on receive event
window.addEventListener("ufs-run-page-scripts", ({ detail }) => {
const { event, ids } = detail;
runScripts(ids, event, path);
runScripts(ids, detail.event, path);
});

// auto run initial event defined in URL search params
if (ids && event) {
let scriptIds = ids.split(",");
runScripts(scriptIds, event, path);
}
})();
const data = await UsefulScriptGlobalPageContext.Extension.getActiveScripts();
console.log(data);
ids = data?.ids?.split(",") || [];
path = data?.path || "";

function getCurrentScriptSrc() {
try {
// cannot get currentScript if script type is module: https://stackoverflow.com/a/45845801/11898496
// return import.meta.url;
throw false;
} catch (e) {
return document.currentScript.src;
// auto run documentStart
if (ids) {
runScripts(ids, "onDocumentStart", path);
}
}
})();

function runScripts(scriptIds, event, path) {
for (let id of scriptIds.filter((_) => _)) {
Expand Down
10 changes: 5 additions & 5 deletions scripts/content-scripts/scripts/ufs_global_webpage_context.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ const UsefulScriptGlobalPageContext = {
);
}
},
getActiveScripts: async function () {
return await UsefulScriptGlobalPageContext.Extension.sendToContentScript(
"getActiveScripts"
);
},
},
DOM: {
// https://stackoverflow.com/a/3381522
Expand Down Expand Up @@ -1341,8 +1346,3 @@ const UsefulScriptsUtils = {
downloadData: UsefulScriptGlobalPageContext.Utils.downloadData,
};
window.UsefulScriptsUtils = UsefulScriptsUtils;

// ================================= Polyfill =================================
// Chrome pre-34
if (!Element.prototype.matches)
Element.prototype.matches = Element.prototype.webkitMatchesSelector;
6 changes: 1 addition & 5 deletions scripts/fb_messengerCount.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,7 @@ export default {

localStorage.ufs_fb_msg_kount = JSON.stringify(ranking);

window.open(
await UsefulScriptGlobalPageContext.Extension.getURL(
"scripts/fb_messengerCount.html"
)
);
window.open(chrome.runtime.getURL("scripts/fb_messengerCount.html"));
} catch (e) {
alert("ERROR: " + e);
} finally {
Expand Down
6 changes: 1 addition & 5 deletions scripts/fb_searchGroupForOther.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,7 @@ export default {
console.log(allGroups);
localStorage.ufs_fb_searchGroupForOther = JSON.stringify(allGroups);
localStorage.ufs_fb_searchGroupForOther_owner = JSON.stringify(info);
window.open(
await UsefulScriptGlobalPageContext.Extension.getURL(
"scripts/fb_searchGroupForOther.html"
)
);
window.open(chrome.runtime.getURL("scripts/fb_searchGroupForOther.html"));
} catch (e) {
alert("ERROR: " + e);
} finally {
Expand Down
6 changes: 1 addition & 5 deletions scripts/fb_searchPageForOther.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,7 @@ export default {
localStorage.ufs_fb_searchPageForOther = JSON.stringify(allPages);
localStorage.ufs_fb_searchPageForOther_owner = JSON.stringify(info);

window.open(
await UsefulScriptGlobalPageContext.Extension.getURL(
"scripts/fb_searchPageForOther.html"
)
);
window.open(chrome.runtime.getURL("scripts/fb_searchPageForOther.html"));
} catch (e) {
alert("ERROR: " + e);
} finally {
Expand Down
2 changes: 2 additions & 0 deletions scripts/fb_whoIsTyping.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ export default {
websocket_instant.addEventListener("message", async function (achunk) {
let utf8_str = textDecoder.decode(achunk.data);

console.log(utf8_str, achunk);

if (
utf8_str.startsWith("1") &&
utf8_str.includes("updateTypingIndicator")
Expand Down
Loading

0 comments on commit ab1c790

Please sign in to comment.