完善一下

This commit is contained in:
go0p
2024-05-14 21:49:22 +08:00
parent 68ae019c7d
commit cb65d57cef
14 changed files with 299 additions and 373 deletions
+12 -11
View File
@@ -18,7 +18,7 @@ chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
case ActionType.DISCONNECT: case ActionType.DISCONNECT:
websocketManager.disconnectWebsocket(); websocketManager.disconnectWebsocket();
break; break;
case ActionType.SETPROXY: case ActionType.SET_PROXY:
chrome.proxy.settings.set({ chrome.proxy.settings.set({
value: { value: {
mode: "fixed_servers", mode: "fixed_servers",
@@ -33,10 +33,10 @@ chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
scope: 'regular', scope: 'regular',
}); });
break; break;
case ActionType.CLEARPROXY: case ActionType.CLEAR_PROXY:
chrome.proxy.settings.clear({}) chrome.proxy.settings.clear({})
break; break;
case ActionType.PROXYSTATUS: case ActionType.PROXY_STATUS:
chrome.proxy.settings.get({}, function (details) { chrome.proxy.settings.get({}, function (details) {
if (details.value && details.value.mode === "fixed_servers") { if (details.value && details.value.mode === "fixed_servers") {
let proxyConfig = details.value.rules.singleProxy; let proxyConfig = details.value.rules.singleProxy;
@@ -49,22 +49,23 @@ chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
} }
}); });
break; break;
case ActionType.INJECTSCRIPT: case ActionType.INJECT_SCRIPT:
chrome.scripting.executeScript({ chrome.scripting.executeScript({
target: {tabId: msg.tabId}, target: {tabId: msg.tabId},
files: ['content.js'] files: ['content.js']
}).then(() => { }).then(() => {
chrome.tabs.sendMessage(msg.tabId, { type: 'INJECT_CODE', value: msg.value }); chrome.tabs.sendMessage(msg.tabId,
{type: ActionType.INJECT_SCRIPT, value: msg.value}
).then(response => {
console.log("response", response)
if (response && response.action === ActionType.TO_EXTENSION_PAGE) {
chrome.runtime.sendMessage(response)
}
})
}).catch(err => { }).catch(err => {
console.error('Script injection failed:', err); console.error('Script injection failed:', err);
}); });
break break
case ActionType.SENDRESFROMPAGE:
chrome.runtime.sendMessage({
action: ActionType.RESTOEVALINTAB,
result: msg.result
})
break
case ActionType.ECHO: case ActionType.ECHO:
console.log("Echo ", msg.result) console.log("Echo ", msg.result)
} }
+5 -5
View File
@@ -4,12 +4,12 @@
} }
window.contentScriptInjected = true; window.contentScriptInjected = true;
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.type === 'INJECT_CODE') { if (request.type === 'yakit_inject_script') {
const injectedScriptURL = chrome.runtime.getURL('inject.js'); const injectedScriptURL = chrome.runtime.getURL('inject.js');
const script = document.createElement('script'); const script = document.createElement('script');
script.src = injectedScriptURL; script.src = injectedScriptURL;
script.onload = () => { script.onload = () => {
window.postMessage({ type: 'CALL_FUNCTION', value: request.value }, '*'); window.postMessage({type: request.value.mode, value: request.value}, '*');
script.remove(); script.remove();
}; };
(document.head || document.documentElement).appendChild(script); (document.head || document.documentElement).appendChild(script);
@@ -19,10 +19,10 @@
} }
window.removeEventListener('message', onMessage); window.removeEventListener('message', onMessage);
// Send the result to the background script // Send the result to the background script
chrome.runtime.sendMessage({ action: 'SEND_RES_FROM_PAGE', result: event.data.result }); // chrome.runtime.sendMessage({ action: 'yakit_to_extension_page', result: event.data.result });
sendResponse({ result: event.data.result }); // 直接向向发送端返回结果
sendResponse({action: 'yakit_to_extension_page', result: event.data.result});
}); });
// Return true to indicate that the response will be sent asynchronously
return true; return true;
} }
}); });
-1
View File
@@ -8,6 +8,5 @@
</head> </head>
<body> <body>
<div id="root"></div> <div id="root"></div>
<iframe src="./sandbox.html" id="sandbox" style="position: absolute;width:0;height:0;border:0;"></iframe>
</body> </body>
</html> </html>
-18
View File
@@ -1,18 +0,0 @@
document.addEventListener('DOMContentLoaded', function () {
const button = document.getElementById('btn');
button.addEventListener('click', clickHandler);
});
function clickHandler() {
const iframe = document.getElementById('sandbox');
iframe.contentWindow.postMessage( "22 * 33", '*');
function listener(event) {
// 这里处理从 iframe 发送回来的数据
console.log('Received message:', event.data);
}
window.addEventListener('message', listener, {once: true});
}
+18 -3
View File
@@ -5,12 +5,27 @@
window.injectedMessageListener = true; window.injectedMessageListener = true;
window.addEventListener('message', function onMessage(event) { window.addEventListener('message', function onMessage(event) {
if (event.source !== window || event.data.type !== 'CALL_FUNCTION') { if (event.source !== window) {
return; return;
} }
const value = event.data.value; let result = "";
const result = window[value.fn_name](value.args); switch (event.data.type) {
case 'CONTENT_CALL_FUNCTION':
const fn_name = event.data.value.fn_name;
const args = event.data.value.args;
result = window[fn_name](args);
break;
case 'CONTENT_EVAL_CODE':
const code = event.data.value.code;
result = eval(code);
// console.log("CONTENT_EVAL_CODE result: ", result);
break;
default:
break;
}
if (result && typeof result === 'object' && Object.keys(result).length > 0) {
window.postMessage({type: 'FROM_PAGE', result: result}, '*'); window.postMessage({type: 'FROM_PAGE', result: result}, '*');
}
}); });
})(); })();
-5
View File
@@ -15,11 +15,6 @@
"service_worker": "background.js", "service_worker": "background.js",
"type": "module" "type": "module"
}, },
"sandbox": {
"pages": [
"sandbox.html"
]
},
"permissions": [ "permissions": [
"webNavigation", "webNavigation",
"activeTab", "activeTab",
-24
View File
@@ -1,24 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="./src/crypto-js.min.js"></script>
</head>
<script>
window.addEventListener('message', async function (event) {
try {
console.log("sandbox event", event)
if (!event.data[0]) {
throw new Error('格式化方法有问题');
}
const func = new Function('obj', event.data[0]);
event.source.window.postMessage(eval(event.data), event.origin);
} catch (e) {
console.error(e);
event.source.window.postMessage(eval(event.data), event.origin);
}
});
</script>
</html>
+5 -8
View File
@@ -2,14 +2,11 @@ export const ActionType = {
CONNECT: 'connect', CONNECT: 'connect',
DISCONNECT: 'disconnect', DISCONNECT: 'disconnect',
STATUS: 'status', STATUS: 'status',
PROXYSTATUS: 'proxystatus', PROXY_STATUS: 'proxy_status',
SETPROXY: 'setproxy', SET_PROXY: 'set_proxy',
CLEARPROXY: 'clearproxy', CLEAR_PROXY: 'clear_proxy',
INJECTSCRIPT: 'INJECT_SCRIPT', INJECT_SCRIPT: 'yakit_inject_script',
SENDRESFROMPAGE: "SEND_RES_FROM_PAGE", TO_EXTENSION_PAGE: "yakit_to_extension_page",
RESTOEVALINTAB: "RES_TO_EVALINTAB",
EVAL: 'eval',
ECHO: 'echo',
} }
export class WebSocketManager { export class WebSocketManager {
-1
View File
File diff suppressed because one or more lines are too long
+2 -4
View File
@@ -3,7 +3,6 @@ import "./App.css";
import {ConfigProvider} from "antd"; import {ConfigProvider} from "antd";
import {Contro} from "@components/Contro"; import {Contro} from "@components/Contro";
import {Proxifier} from "@components/Proxifier"; import {Proxifier} from "@components/Proxifier";
import {Eval} from "@components/Eval";
import {EvalInTab} from "@components/EvalInTab"; import {EvalInTab} from "@components/EvalInTab";
function App() { function App() {
@@ -16,10 +15,9 @@ function App() {
}} }}
> >
<div className="App"> <div className="App">
{/*<Contro/>*/} <Contro/>
{/*<Proxifier/>*/} <Proxifier/>
<Eval/>
<EvalInTab/> <EvalInTab/>
</div> </div>
</ConfigProvider> </ConfigProvider>
+4 -2
View File
@@ -10,9 +10,11 @@ import {
} from "@assets/icon/icon"; } from "@assets/icon/icon";
import {wsc} from "@network/chrome"; import {wsc} from "@network/chrome";
import "./Contro.css"; import "./Contro.css";
import { ActionType } from "../../public/socket"; import {ActionType} from "@network/chrome";
interface ControProps {
}
interface ControProps {}
export const Contro: React.FC<ControProps> = () => { export const Contro: React.FC<ControProps> = () => {
const [isEdit, setIsEdit] = useState<boolean>(false); const [isEdit, setIsEdit] = useState<boolean>(false);
const [connected, setConnected] = useState(false); const [connected, setConnected] = useState(false);
-51
View File
@@ -1,51 +0,0 @@
import React, {useEffect, useState} from "react";
import TextArea from "antd/lib/input/TextArea";
import {Button} from "antd";
interface EvalProps {
}
export const Eval: React.FC<EvalProps> = () => {
const [inputData, setInputData] = useState(""); // 状态用于存储 textarea 输入的数据
useEffect(() => {
const handleMessage = (event: MessageEvent) => {
// 检查消息来源是否安全
// if (event.origin !== "http://example.com") { // 适当替换为你的期望源
// return;
// }
console.log(event.data)
alert(`Received message: ${event.data}`);
}
// 添加事件监听器
window.addEventListener('message', handleMessage);
return () => {
window.removeEventListener('message', handleMessage);
};
}, []);
// 处理按钮点击事件
const handleClick = () => {
const iframe = document.getElementById('sandbox') as HTMLIFrameElement; // 正确的类型断言
if (iframe?.contentWindow) {
iframe.contentWindow.postMessage({fn: 'Encrypt', args: '111111'}, '*'); // 发送用户输入的数据到 iframe
}
};
// 更新 textarea 输入
const handleInputChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
setInputData(event.target.value);
};
return (
<div>
<TextArea
value={inputData}
onChange={handleInputChange}
placeholder="Enter your expression (e.g., 22 * 33)"
/>
<Button onClick={handleClick}>Click me</Button>
</div>
);
}
+42 -31
View File
@@ -1,37 +1,22 @@
import React, {useEffect, useState} from "react"; import React, {useEffect, useState} from "react";
import { Button } from "antd"; import {Button, Input} from "antd";
import TextArea from "antd/lib/input/TextArea"; import TextArea from "antd/lib/input/TextArea";
import {wsc} from "@network/chrome"; import {wsc} from "@network/chrome";
import { ActionType } from "../../public/socket"; import {ActionType} from "@network/chrome";
interface EvalInTabProps {} interface EvalInTabProps {
}
export const EvalInTab: React.FC<EvalInTabProps> = () => { export const EvalInTab: React.FC<EvalInTabProps> = () => {
const [inputData, setInputData] = useState(""); const [funcName, setFuncName] = useState("");
const [inputArgsData, setInputArgsData] = useState("");
// useEffect(() => { const [code, setCode] = useState("");
// // 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(() => { useEffect(() => {
wsc.onWSCMessage((message) => { wsc.onWSCMessage((message) => {
if (message.action === ActionType.RESTOEVALINTAB) { if (message.action === ActionType.TO_EXTENSION_PAGE) {
console.log("res:", message.result); console.log("res:", message.result);
alert("from content script: " + JSON.stringify(message.result));
} }
}); });
}, []); }, []);
@@ -39,26 +24,52 @@ export const EvalInTab: React.FC<EvalInTabProps> = () => {
const handleClick = async () => { const handleClick = async () => {
try { try {
const tabId = await wsc.getTabId(); const tabId = await wsc.getTabId();
chrome.runtime.sendMessage({ await chrome.runtime.sendMessage({
action: ActionType.INJECTSCRIPT, action: ActionType.INJECT_SCRIPT,
tabId: tabId, tabId: tabId,
value: { fn_name: "Encrypt", args: inputData }, value: {mode: "CONTENT_CALL_FUNCTION", fn_name: funcName, args: inputArgsData},
}); });
} catch (error) {} } catch (error) {
}
}; };
const handleInputChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => { const handleInputChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
setInputData(event.target.value); setInputArgsData(event.target.value);
}; };
const handleEvalCodeClick = async () => {
try {
const tabId = await wsc.getTabId();
await chrome.runtime.sendMessage({
action: ActionType.INJECT_SCRIPT,
tabId: tabId,
value: {mode: "CONTENT_EVAL_CODE", code: code},
});
} catch (error) {
}
}
return ( return (
<div> <div>
<Input
value={funcName}
onChange={(e) => setFuncName(e.target.value)}
placeholder="Enter function name"
></Input>
<TextArea <TextArea
value={inputData} value={inputArgsData}
onChange={handleInputChange} onChange={handleInputChange}
placeholder="Enter your expression (e.g., 22 * 33)" placeholder="Enter your expression (e.g., 22 * 33)"
/> />
<Button onClick={handleClick}>eval in tab me</Button> <Button onClick={handleClick}>eval func in tab</Button>
<TextArea
value={code}
onChange={(e) => setCode(e.target.value)}
placeholder="Enter your expression (e.g., 22 * 33)"
/>
<Button onClick={handleEvalCodeClick}>eval code in tab</Button>
</div> </div>
); );
}; };
+10 -8
View File
@@ -1,10 +1,12 @@
enum ActionType { export enum ActionType {
CONNECT = 'connect', CONNECT = 'connect',
DISCONNECT = 'disconnect', DISCONNECT = 'disconnect',
STATUS = 'status', STATUS = 'status',
PROXYSTATUS = 'proxystatus', PROXY_STATUS = 'proxy_status',
SETPROXY = 'setproxy', SET_PROXY = 'set_proxy',
CLEARPROXY = 'clearproxy' CLEAR_PROXY = 'clear_proxy',
INJECT_SCRIPT = 'yakit_inject_script',
TO_EXTENSION_PAGE = "yakit_to_extension_page",
} }
export namespace wsc { export namespace wsc {
@@ -30,7 +32,7 @@ export namespace wsc {
export function updateProxyStatus() { export function updateProxyStatus() {
chrome.runtime.sendMessage({ chrome.runtime.sendMessage({
action: ActionType.PROXYSTATUS, action: ActionType.PROXY_STATUS,
}); });
} }
@@ -43,16 +45,16 @@ export namespace wsc {
} }
export function setproxy(scheme: string, host: string, port: number) { export function setproxy(scheme: string, host: string, port: number) {
chrome.runtime.sendMessage({action: ActionType.SETPROXY, scheme, host, port}) chrome.runtime.sendMessage({action: ActionType.SET_PROXY, scheme, host, port})
} }
export function clearproxy() { export function clearproxy() {
chrome.runtime.sendMessage({action: ActionType.CLEARPROXY}) chrome.runtime.sendMessage({action: ActionType.CLEAR_PROXY})
} }
export function getTabId() { export function getTabId() {
return new Promise<number>((resolve, reject) => { return new Promise<number>((resolve, reject) => {
chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) { chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
if (tabs.length) { if (tabs.length) {
resolve(tabs[0].id); resolve(tabs[0].id);
} else { } else {