diff --git a/public/inject.js b/public/inject.js index 3afc196..a4fed7a 100644 --- a/public/inject.js +++ b/public/inject.js @@ -6,14 +6,21 @@ * @see {@link http://stackoverflow.com/questions/20499994/access-window-variable-from-content-script} */ function injectScript(file_path, tag) { - var node = document.getElementsByTagName(tag)[0]; + const node = document.getElementsByTagName(tag)[0]; if (!node) { console.error('The "' + tag + '" tag is not available in the document.'); return; } - var script = document.createElement('script'); + // 移除之前的脚本 + const oldScript = document.getElementById('yakit-injected-script'); + if (oldScript) { + node.removeChild(oldScript); + } + const script = document.createElement('script'); script.setAttribute('type', 'text/javascript'); script.setAttribute('src', file_path); + script.setAttribute('id', 'yakit-injected-script'); + node.appendChild(script); } diff --git a/src/components/EvalInTab.tsx b/src/components/EvalInTab.tsx index e38e67a..fffab70 100644 --- a/src/components/EvalInTab.tsx +++ b/src/components/EvalInTab.tsx @@ -1,6 +1,7 @@ import React, {useEffect, useState} from "react"; import {Button} from "antd"; import TextArea from "antd/lib/input/TextArea"; +import {wsc} from "@network/chrome"; interface EvalInTabProps { } @@ -18,28 +19,28 @@ export const EvalInTab: React.FC = () => { port.onDisconnect.addListener(function () { console.error("Disconnected from port."); }); - port.postMessage({ type: "TEST", fn_name: "Encrypt", args: inputData }); + port.postMessage({type: "TEST", fn_name: "Encrypt", args: inputData}); }; chrome.runtime.onConnect.addListener(onConnectListener); - return () => { - chrome.runtime.onConnect.removeListener(onConnectListener); - }; + // return () => { + // chrome.runtime.onConnect.removeListener(onConnectListener); + // }; }, [inputData]); - const handleClick = () => { - - - chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) { - console.log(tabs[0].title); + const handleClick = async () => { + if (!isScriptInjected) { chrome.scripting.executeScript({ - target: { tabId: tabs[0].id }, + target: {tabId: await wsc.getTabId()}, files: ['inject.js'], }).then(injectResults => { console.log(injectResults) + setIsScriptInjected(true); }); - }); + } + console.log("injected script") + }; const handleInputChange = (event: React.ChangeEvent) => { diff --git a/src/network/chrome.ts b/src/network/chrome.ts index e3371cf..93b2b62 100644 --- a/src/network/chrome.ts +++ b/src/network/chrome.ts @@ -50,5 +50,15 @@ export namespace wsc { chrome.runtime.sendMessage({action: ActionType.CLEARPROXY}) } - + export function getTabId() { + return new Promise((resolve, reject) => { + chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) { + if (tabs.length) { + resolve(tabs[0].id); + } else { + reject('No active tab found'); + } + }); + }); + } }