mirror of
https://github.com/yaklang/yaklang-chrome-extension.git
synced 2026-09-22 03:10:43 +08:00
eval in page context
This commit is contained in:
@@ -138,6 +138,7 @@
|
||||
"@babel/core": "^7.24.1",
|
||||
"@babel/preset-env": "^7.24.1",
|
||||
"@babel/preset-react": "^7.24.1",
|
||||
"@types/chrome": "^0.0.268",
|
||||
"babel-loader": "^9.1.3",
|
||||
"copy-webpack-plugin": "^12.0.2",
|
||||
"cross-env": "^7.0.3",
|
||||
|
||||
+40
-13
@@ -1,4 +1,4 @@
|
||||
import {ActionType, WebSocketManager} from './connect.js';
|
||||
import {ActionType, WebSocketManager} from './socket.js';
|
||||
|
||||
|
||||
console.info("Chrome Extenstion Background is loaded")
|
||||
@@ -49,21 +49,48 @@ chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
|
||||
}
|
||||
});
|
||||
break;
|
||||
case ActionType.ECHO:
|
||||
console.log("Echo ", msg.result)
|
||||
}
|
||||
|
||||
})
|
||||
|
||||
|
||||
chrome.runtime.onInstalled.addListener(() => {
|
||||
chrome.scripting.registerContentScripts([{
|
||||
id: 'myScript',
|
||||
matches: ['<all_urls>'], // 根据需要调整匹配模式
|
||||
js: ['inject.js'],
|
||||
runAt: 'document_start'
|
||||
}], (result) => {
|
||||
if (chrome.runtime.lastError) {
|
||||
console.error(`Error registering script: ${chrome.runtime.lastError.message}`);
|
||||
const pageFunction = (code) => {
|
||||
chrome.runtime.sendMessage({code}, response => {
|
||||
if (response && response.success) {
|
||||
console.log('Result:', response.result);
|
||||
} else {
|
||||
console.log('Script registered', result);
|
||||
console.error('Error:', response.error);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// chrome.runtime.onInstalled.addListener(() => {
|
||||
// chrome.scripting.registerContentScripts([{
|
||||
// id: 'myScript',
|
||||
// matches: ['<all_urls>'], // 根据需要调整匹配模式
|
||||
// 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-script");
|
||||
// port.onMessage.addListener(function (msg) {
|
||||
// console.log("on connect", msg)
|
||||
// });
|
||||
// port.onDisconnect.addListener(function () {
|
||||
// console.error("Disconnected from port.");
|
||||
// });
|
||||
// // port.postMessage({action: "TEST POST MESSAGE"});
|
||||
//
|
||||
// });
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
console.log("Loaded content.js")
|
||||
|
||||
window.addEventListener("message", (event) => {
|
||||
if (event.data.type && (event.data.type === "TEST")) {
|
||||
console.log(event)
|
||||
const name = event.data.fn_name
|
||||
const args = event.data.args
|
||||
const a = (fn, args) => {
|
||||
return window[fn](args)
|
||||
}
|
||||
const zz = a(name, args)
|
||||
window.postMessage({type: "FROM_PAGE", text: zz}, "*")
|
||||
}
|
||||
}, );
|
||||
+1
-1
@@ -7,7 +7,7 @@
|
||||
<title>React App</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root"></div>
|
||||
<iframe src="./sandbox.html" id="sandbox" style="position: absolute;width:0;height:0;border:0;"></iframe>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
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});
|
||||
|
||||
}
|
||||
+46
-12
@@ -1,13 +1,47 @@
|
||||
console.log('This runs at document start, before any document content is parsed.');
|
||||
// 保存原始的console.log函数的引用
|
||||
const originalConsoleLog = console.log;
|
||||
|
||||
// 重写console.log
|
||||
console.log = function (message) {
|
||||
// 调用原始的console.log函数
|
||||
originalConsoleLog("trying to open " + message + " window.");
|
||||
};
|
||||
|
||||
window.open = function (url) {
|
||||
console.log("trying to open " + url + " window.");
|
||||
/**
|
||||
* injectScript - Inject internal script to available access to the `window`
|
||||
*
|
||||
* @param {type} file_path Local path of the internal script.
|
||||
* @param {type} tag The tag as string, where the script will be append (default: 'body').
|
||||
* @see {@link http://stackoverflow.com/questions/20499994/access-window-variable-from-content-script}
|
||||
*/
|
||||
function injectScript(file_path, tag) {
|
||||
var node = document.getElementsByTagName(tag)[0];
|
||||
if (!node) {
|
||||
console.error('The "' + tag + '" tag is not available in the document.');
|
||||
return;
|
||||
}
|
||||
var script = document.createElement('script');
|
||||
script.setAttribute('type', 'text/javascript');
|
||||
script.setAttribute('src', file_path);
|
||||
node.appendChild(script);
|
||||
}
|
||||
|
||||
// document.addEventListener('DOMContentLoaded', function () {
|
||||
injectScript(chrome.runtime.getURL('content.js'), 'body');
|
||||
|
||||
const port = chrome.runtime.connect({name: "content-script"});
|
||||
|
||||
port.onDisconnect.addListener(function () {
|
||||
console.error("Disconnected from port.");
|
||||
});
|
||||
|
||||
port.onMessage.addListener(function (msg) {
|
||||
console.log("我听到了成功的回响 :", msg);
|
||||
window.postMessage(msg, "*")
|
||||
});
|
||||
|
||||
window.addEventListener("message", (event) => {
|
||||
// We only accept messages from ourselves
|
||||
if (event.source !== window) {
|
||||
return;
|
||||
}
|
||||
if (event.data.type && (event.data.type === "FROM_PAGE")) {
|
||||
console.log(event)
|
||||
console.log("Content script received: " + event.data.text);
|
||||
if (port && port.postMessage) {
|
||||
port.postMessage(event.data.text);
|
||||
}
|
||||
}
|
||||
}, );
|
||||
// });
|
||||
+10
-7
@@ -15,6 +15,11 @@
|
||||
"service_worker": "background.js",
|
||||
"type": "module"
|
||||
},
|
||||
"sandbox": {
|
||||
"pages": [
|
||||
"sandbox.html"
|
||||
]
|
||||
},
|
||||
"permissions": [
|
||||
"webNavigation",
|
||||
"activeTab",
|
||||
@@ -27,14 +32,12 @@
|
||||
"host_permissions": [
|
||||
"<all_urls>"
|
||||
],
|
||||
"content_scripts": [
|
||||
|
||||
"web_accessible_resources": [
|
||||
{
|
||||
"matches": [
|
||||
"<all_urls>"
|
||||
],
|
||||
"js": [
|
||||
"content.js"
|
||||
]
|
||||
"resources": ["content.js"],
|
||||
"matches": ["<all_urls>"],
|
||||
"use_dynamic_url": true
|
||||
}
|
||||
],
|
||||
"icons": {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
<!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>
|
||||
@@ -4,7 +4,9 @@ export const ActionType = {
|
||||
STATUS: 'status',
|
||||
PROXYSTATUS: 'proxystatus',
|
||||
SETPROXY: 'setproxy',
|
||||
CLEARPROXY: 'clearproxy'
|
||||
CLEARPROXY: 'clearproxy',
|
||||
EVAL: 'eval',
|
||||
ECHO: 'echo',
|
||||
}
|
||||
|
||||
export class WebSocketManager {
|
||||
@@ -78,34 +80,34 @@ export class WebSocketManager {
|
||||
handleMessage(message) {
|
||||
console.log("message", message)
|
||||
// 解析消息
|
||||
try {
|
||||
// 解析从WebSocket接收到的JSON数据
|
||||
let code = message;
|
||||
getTabId().then((tabId) => {
|
||||
// 确保tabId和code有效
|
||||
if (typeof tabId === 'number' && typeof code === 'string') {
|
||||
chrome.webNavigation.getAllFrames({tabId: tabId}, function(frames) {
|
||||
for (let frame of frames) {
|
||||
console.log(`Frame ID: ${frame.frameId} with URL: ${frame.url}`);
|
||||
}
|
||||
});
|
||||
// 在指定的tabId上执行脚本
|
||||
chrome.scripting.executeScript({
|
||||
target: {tabId: tabId},
|
||||
// function: getTitle,
|
||||
function: log,
|
||||
args: [code]
|
||||
}, (injectionResults) => {
|
||||
// 处理脚本执行的结果,如日志记录等
|
||||
console.log('Script executed:', injectionResults);
|
||||
});
|
||||
} else {
|
||||
console.error('Received malformed message:', message);
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Error parsing message from WebSocket:', err);
|
||||
}
|
||||
// try {
|
||||
// // 解析从WebSocket接收到的JSON数据
|
||||
// let code = message;
|
||||
// getTabId().then((tabId) => {
|
||||
// // 确保tabId和code有效
|
||||
// if (typeof tabId === 'number' && typeof code === 'string') {
|
||||
// chrome.webNavigation.getAllFrames({tabId: tabId}, function(frames) {
|
||||
// for (let frame of frames) {
|
||||
// console.log(`Frame ID: ${frame.frameId} with URL: ${frame.url}`);
|
||||
// }
|
||||
// });
|
||||
// // 在指定的tabId上执行脚本
|
||||
// chrome.scripting.executeScript({
|
||||
// target: {tabId: tabId},
|
||||
// // function: getTitle,
|
||||
// function: log,
|
||||
// args: [code]
|
||||
// }, (injectionResults) => {
|
||||
// // 处理脚本执行的结果,如日志记录等
|
||||
// console.log('Script executed:', injectionResults);
|
||||
// });
|
||||
// } else {
|
||||
// console.error('Received malformed message:', message);
|
||||
// }
|
||||
// });
|
||||
// } catch (err) {
|
||||
// console.error('Error parsing message from WebSocket:', err);
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,9 +119,9 @@ function log(message) {
|
||||
return console.log(message);
|
||||
}
|
||||
|
||||
function getTabId() {
|
||||
export const getTabId = () => {
|
||||
return new Promise((resolve, reject) => {
|
||||
chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
|
||||
chrome.tabs.query({active: true, lastFocusedWindow: true}, (tabs) => {
|
||||
if (tabs.length) {
|
||||
resolve(tabs[0].id);
|
||||
} else {
|
||||
Vendored
+1
File diff suppressed because one or more lines are too long
+10
-5
@@ -1,9 +1,11 @@
|
||||
import React from "react";
|
||||
import "./App.css";
|
||||
import { ConfigProvider } from "antd";
|
||||
import { Contro } from "@components/Contro";
|
||||
import { Proxifier } from "@components/Proxifier";
|
||||
import { Controller } from "./components/Controller";
|
||||
import {ConfigProvider} from "antd";
|
||||
import {Contro} from "@components/Contro";
|
||||
import {Proxifier} from "@components/Proxifier";
|
||||
import {Controller} from "./components/Controller";
|
||||
import {Eval} from "@components/Eval";
|
||||
import {EvalInTab} from "@components/EvalInTab";
|
||||
|
||||
function App() {
|
||||
return (
|
||||
@@ -15,8 +17,11 @@ function App() {
|
||||
}}
|
||||
>
|
||||
<div className="App">
|
||||
<Contro />
|
||||
<Contro/>
|
||||
<Proxifier/>
|
||||
|
||||
<Eval/>
|
||||
<EvalInTab/>
|
||||
{/* <Controller/> */}
|
||||
</div>
|
||||
</ConfigProvider>
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
} from "@assets/icon/icon";
|
||||
import { wsc } from "@network/chrome";
|
||||
import "./Contro.css";
|
||||
import { ActionType } from "../../public/connect";
|
||||
import { ActionType } from "../../public/socket";
|
||||
|
||||
interface ControProps {}
|
||||
export const Contro: React.FC<ControProps> = () => {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import React, {useEffect, useState} from "react";
|
||||
import {Button} from "antd";
|
||||
import TextArea from "antd/lib/input/TextArea";
|
||||
|
||||
interface EvalInTabProps {
|
||||
}
|
||||
|
||||
export const EvalInTab: React.FC<EvalInTabProps> = () => {
|
||||
const [inputData, setInputData] = useState("");
|
||||
const [isScriptInjected, setIsScriptInjected] = useState(false);
|
||||
|
||||
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]);
|
||||
|
||||
const handleClick = () => {
|
||||
|
||||
|
||||
chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) {
|
||||
console.log(tabs[0].title);
|
||||
chrome.scripting.executeScript({
|
||||
target: { tabId: tabs[0].id },
|
||||
files: ['inject.js'],
|
||||
}).then(injectResults => {
|
||||
console.log(injectResults)
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
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}>eval in tab me</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,3 @@
|
||||
import {chrome} from "./chromeapi";
|
||||
|
||||
enum ActionType {
|
||||
CONNECT = 'connect',
|
||||
DISCONNECT = 'disconnect',
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
export interface MockMessageSender {
|
||||
id?: string;
|
||||
}
|
||||
|
||||
export interface MockChromeRuntime {
|
||||
sendMessage: (message: any, responseCallback?: (response: any) => void) => void;
|
||||
onMessage: {
|
||||
addListener: (callback: (message: any, sender: MockMessageSender, sendResponse: (response?: any) => void) => void) => void;
|
||||
};
|
||||
}
|
||||
|
||||
export interface MockChromeProxy {
|
||||
settings: {
|
||||
set: (value: { value: any, scope: string }) => void;
|
||||
get: (details: { incognito?: boolean }, callback: (config: any) => void) => void;
|
||||
};
|
||||
}
|
||||
|
||||
export interface MockChromeTabs {
|
||||
query: (queryInfo: any, callback: (result: any) => void) => void;
|
||||
create: (createProperties: any, callback?: (tab: any) => void) => void;
|
||||
}
|
||||
|
||||
export interface MockChrome {
|
||||
runtime: MockChromeRuntime;
|
||||
proxy: MockChromeProxy;
|
||||
tabs: MockChromeTabs;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
chrome?: any;
|
||||
}
|
||||
}
|
||||
|
||||
export const chrome: MockChrome = typeof window.chrome !== 'undefined' && window.chrome.runtime ? window.chrome : {
|
||||
runtime: {
|
||||
sendMessage: (message, responseCallback) => {
|
||||
console.log('Mock sendMessage called with:', message);
|
||||
if (responseCallback) responseCallback('response from mock');
|
||||
},
|
||||
onMessage: {
|
||||
addListener: (callback) => {
|
||||
console.log('Mock onMessage.addListener called');
|
||||
callback({connected: true}, undefined, undefined)
|
||||
// You can simulate incoming messages here if needed
|
||||
}
|
||||
}
|
||||
},
|
||||
proxy: {
|
||||
settings: {
|
||||
set: (value) => {
|
||||
console.log('Mock proxy settings set with:', value);
|
||||
},
|
||||
get: (details, callback) => {
|
||||
console.log('Mock proxy settings get called');
|
||||
// Simulate proxy settings response
|
||||
callback({mode: 'direct'});
|
||||
}
|
||||
}
|
||||
},
|
||||
tabs: {
|
||||
query: (queryInfo, callback) => {
|
||||
console.log('Mock tabs.query called with:', queryInfo);
|
||||
// Simulate a tab query response
|
||||
callback([{id: 1, url: 'http://example.com', title: 'Example'}]);
|
||||
},
|
||||
create: (createProperties, callback) => {
|
||||
console.log('Mock tabs.create called with:', createProperties);
|
||||
// Simulate creating a tab
|
||||
if (callback) callback({id: 2, url: createProperties.url});
|
||||
}
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user