From 7c1cdd562c4126f5e46a86ff42366f650a22744b Mon Sep 17 00:00:00 2001 From: song_xiao_lin Date: Tue, 14 May 2024 15:53:15 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E6=B3=A8=E5=85=A5js?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- public/background.js | 52 ++++++--------- public/content.js | 44 ++++++++----- public/inject.js | 74 +++++----------------- public/manifest.json | 2 +- public/socket.js | 3 + src/components/EvalInTab.tsx | 118 ++++++++++++++++------------------- 6 files changed, 120 insertions(+), 173 deletions(-) diff --git a/public/background.js b/public/background.js index cecc2df..dd4fa3d 100644 --- a/public/background.js +++ b/public/background.js @@ -1,4 +1,4 @@ -import {ActionType, WebSocketManager} from './socket.js'; +import { ActionType, WebSocketManager } from './socket.js'; console.info("Chrome Extenstion Background is loaded") @@ -45,10 +45,26 @@ chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) { proxy: `${proxyConfig.scheme}://${proxyConfig.host}:${proxyConfig.port}` }) } else { - chrome.runtime.sendMessage({enable: false, proxy: ""}) + chrome.runtime.sendMessage({ enable: false, proxy: "" }) } }); break; + case ActionType.INJECTSCRIPT: + chrome.scripting.executeScript({ + target: { tabId: msg.tabId }, + files: ['content.js'] + }).then(() => { + chrome.tabs.sendMessage(msg.tabId, { type: 'INJECT_CODE', value: msg.value }); + }).catch(err => { + console.error('Script injection failed:', err); + }); + break + case ActionType.SENDRESFROMPAGE: + chrome.runtime.sendMessage({ + action: ActionType.RESTOEVALINTAB, + result: msg.result + }) + break case ActionType.ECHO: console.log("Echo ", msg.result) } @@ -56,7 +72,7 @@ chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) { }) const pageFunction = (code) => { - chrome.runtime.sendMessage({code}, response => { + chrome.runtime.sendMessage({ code }, response => { if (response && response.success) { console.log('Result:', response.result); } else { @@ -64,33 +80,3 @@ const pageFunction = (code) => { } }); } - -// chrome.runtime.onInstalled.addListener(() => { -// chrome.scripting.registerContentScripts([{ -// id: 'myScript', -// matches: [''], // 根据需要调整匹配模式 -// js: ['content2.js'], -// // world: 'MAIN', -// // runAt: 'document_start' -// }], (result) => { -// if (chrome.runtime.lastError) { -// console.error(`Error registering script: ${chrome.runtime.lastError.message}`); -// } else { -// console.log('Script registered', result); -// } -// }); -// }); - -chrome.runtime.onConnect.addListener(function (port) { - console.assert(port.name === "content-to-ex"); - if (!port.hasListener) { - port.onMessage.addListener(function (msg) { - console.log("[content-to-ex]", msg) - }); - port.onDisconnect.addListener(function () { - console.error("[content-to-ex] Disconnected from port."); - }); - // port.postMessage({action: "TEST POST MESSAGE"}); - port.hasListener = true; - } -}); diff --git a/public/content.js b/public/content.js index d0d22ad..d80f3c4 100644 --- a/public/content.js +++ b/public/content.js @@ -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; -} +})() + diff --git a/public/inject.js b/public/inject.js index b6de250..004c6c8 100644 --- a/public/inject.js +++ b/public/inject.js @@ -1,63 +1,17 @@ -function injectScript(src, id, message) { - return new Promise((resolve) => { - // Inject a script tag into the page to access methods of the window object - const script = document.createElement('script') +(() => { + if (window.injectedMessageListener) { + return; + } + window.injectedMessageListener = true; - script.onload = () => { - const onMessage = ({ data }) => { - console.log(data) - if (!data.yakitex || !data.yakitex.msg) { - return - } - - window.removeEventListener('message', onMessage) - - // resolve(data.yakitex.msg) - - script.remove() - } - - window.addEventListener('message', onMessage) - - window.postMessage({ - yakitex: message, - }) - } - - script.setAttribute('src', chrome.runtime.getURL(src)) - - document.body.appendChild(script) - }) -} - -if (!window.hasAddedMessageListener2) { - window.addEventListener("message", (event) => { - if (event.data.type && (event.data.type === "FROM_PAGE")) { - const port = chrome.runtime.connect({ name: "content-to-ex" }); - port.postMessage(event.data.text); - port.disconnect(); - return - } - }) - window.hasAddedMessageListener2 = true; -} - - -function connectAddListenerFun(port) { - console.assert(port.name === "ex-to-content"); - if (!port.hasListener) { - port.onMessage.addListener(function (msg) { - console.log(111111111111111); - injectScript('content.js', 'sender', { yakitex: "123", id: "yakit", msg: msg }) - }); - - port.onDisconnect.addListener(function () { - console.error("[ex-to-content] Disconnected from port."); - }); - port.hasListener = true + window.addEventListener('message', function onMessage(event) { + if (event.source !== window || event.data.type !== 'CALL_FUNCTION') { + return; } -} -if (!chrome.runtime.onConnect.hasListener(connectAddListenerFun)) { - chrome.runtime.onConnect.addListener(connectAddListenerFun); -} + const value = event.data.value; + const result = window[value.fn_name](value.args); + window.postMessage({ type: 'FROM_PAGE', result: result }, '*'); + }); +})(); + diff --git a/public/manifest.json b/public/manifest.json index 51cca74..46547ed 100644 --- a/public/manifest.json +++ b/public/manifest.json @@ -35,7 +35,7 @@ "web_accessible_resources": [ { - "resources": ["content.js"], + "resources": ["inject.js"], "matches": [""], "use_dynamic_url": true } diff --git a/public/socket.js b/public/socket.js index d9c206b..788014b 100644 --- a/public/socket.js +++ b/public/socket.js @@ -5,6 +5,9 @@ export const ActionType = { PROXYSTATUS: 'proxystatus', SETPROXY: 'setproxy', CLEARPROXY: 'clearproxy', + INJECTSCRIPT: 'INJECT_SCRIPT', + SENDRESFROMPAGE: "SEND_RES_FROM_PAGE", + RESTOEVALINTAB: "RES_TO_EVALINTAB", EVAL: 'eval', ECHO: 'echo', } diff --git a/src/components/EvalInTab.tsx b/src/components/EvalInTab.tsx index 8e5342b..8d75ca7 100644 --- a/src/components/EvalInTab.tsx +++ b/src/components/EvalInTab.tsx @@ -1,72 +1,64 @@ -import React, {useEffect, useState} from "react"; -import {Button} from "antd"; +import React, { useEffect, useState } from "react"; +import { Button } from "antd"; import TextArea from "antd/lib/input/TextArea"; -import {wsc} from "@network/chrome"; +import { wsc } from "@network/chrome"; +import { ActionType } from "../../public/socket"; -interface EvalInTabProps { -} +interface EvalInTabProps {} export const EvalInTab: React.FC = () => { - const [inputData, setInputData] = useState(""); - const [port, setPort] = useState() + const [inputData, setInputData] = useState(""); - // useEffect(() => { - // // const onConnectListener = (port: chrome.runtime.Port) => { - // // console.assert(port.name === "content-script"); - // // port.onMessage.addListener(function (msg) { - // // console.log("on connect", msg) - // // }); - // // port.onDisconnect.addListener(function () { - // // console.error("Disconnected from port."); - // // }); - // // port.postMessage({type: "TEST", fn_name: "Encrypt", args: inputData}); - // // }; - // // - // // chrome.runtime.onConnect.addListener(onConnectListener); - // - // // return () => { - // // chrome.runtime.onConnect.removeListener(onConnectListener); - // // }; - // }, [inputData]); + // useEffect(() => { + // // const onConnectListener = (port: chrome.runtime.Port) => { + // // console.assert(port.name === "content-script"); + // // port.onMessage.addListener(function (msg) { + // // console.log("on connect", msg) + // // }); + // // port.onDisconnect.addListener(function () { + // // console.error("Disconnected from port."); + // // }); + // // port.postMessage({type: "TEST", fn_name: "Encrypt", args: inputData}); + // // }; + // // + // // chrome.runtime.onConnect.addListener(onConnectListener); + // + // // return () => { + // // chrome.runtime.onConnect.removeListener(onConnectListener); + // // }; + // }, [inputData]); - useEffect(() => { - const injectFun = async () => { - const tabId = await wsc.getTabId(); - chrome.scripting.executeScript({ - target: {tabId: tabId}, - files: ['inject.js'], - }).then(() => { - const newPort = chrome.tabs.connect(tabId, {name: "ex-to-content"}) - setPort(newPort) - newPort.onMessage.addListener(function (msg) { - console.log(msg) - }) - }) - } - injectFun() - return () => { - if (port) { - port.disconnect() - } - } - }, []) + useEffect(() => { + wsc.onWSCMessage((message) => { + if (message.action === ActionType.RESTOEVALINTAB) { + console.log("res:", message.result); + } + }); + }, []); - const handleClick = async () => { - port.postMessage({type: "TEST", fn_name: "Encrypt", args: inputData}); - }; + const handleClick = async () => { + try { + const tabId = await wsc.getTabId(); + chrome.runtime.sendMessage({ + action: ActionType.INJECTSCRIPT, + tabId: tabId, + value: { fn_name: "Encrypt", args: inputData }, + }); + } catch (error) {} + }; - const handleInputChange = (event: React.ChangeEvent) => { - setInputData(event.target.value); - }; + const handleInputChange = (event: React.ChangeEvent) => { + setInputData(event.target.value); + }; - return ( -
-