fix: 注入js

This commit is contained in:
song_xiao_lin
2024-05-14 15:53:15 +08:00
parent ed1005936b
commit 01f04e3e56
6 changed files with 120 additions and 173 deletions
+28 -16
View File
@@ -1,18 +1,30 @@
console.log("Loaded content.js")
if (!window.hasAddedMessageListener) {
window.addEventListener("message", (event) => {
if (event.data?.yakitex?.msg && (event.data.yakitex.msg.type === "TEST")) {
const name = event.data.yakitex.msg.fn_name;
const args = event.data.yakitex.msg.args;
const a = (fn, args) => {
return window[fn](args);
}
const zz = a(name, args);
console.log("res ", zz);
window.postMessage({type: "FROM_PAGE", text: zz}, "*");
return
(() => {
if (window.contentScriptInjected) {
return;
}
window.contentScriptInjected = true;
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.type === 'INJECT_CODE') {
const injectedScriptURL = chrome.runtime.getURL('inject.js');
const script = document.createElement('script');
script.src = injectedScriptURL;
script.onload = () => {
window.postMessage({ type: 'CALL_FUNCTION', value: request.value }, '*');
script.remove();
};
(document.head || document.documentElement).appendChild(script);
window.addEventListener('message', function onMessage(event) {
if (event.source !== window || event.data.type !== 'FROM_PAGE') {
return;
}
window.removeEventListener('message', onMessage);
// Send the result to the background script
chrome.runtime.sendMessage({ action: 'SEND_RES_FROM_PAGE', result: event.data.result });
sendResponse({ result: event.data.result });
});
// Return true to indicate that the response will be sent asynchronously
return true;
}
});
window.hasAddedMessageListener = true;
}
})()