90 lines
2.5 KiB
JavaScript
90 lines
2.5 KiB
JavaScript
const axios = require('axios');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
|
|
async function executeScriptOnCurrentTab(scriptFile) {
|
|
try {
|
|
// Get list of tabs from Chrome DevTools Protocol
|
|
const response = await axios.get('http://localhost:9222/json');
|
|
const tabs = response.data;
|
|
|
|
// Find the first page tab (not extensions or devtools)
|
|
const targetTab = tabs.find(tab => tab.type === 'page');
|
|
|
|
if (!targetTab) {
|
|
console.error('No active page tab found. Make sure Chrome is running with --remote-debugging-port=9222');
|
|
process.exit(1);
|
|
}
|
|
|
|
console.log(`Found tab: ${targetTab.title}`);
|
|
console.log(`URL: ${targetTab.url}`);
|
|
|
|
// Read the script content
|
|
const scriptContent = fs.readFileSync(scriptFile, 'utf-8');
|
|
|
|
// Connect to the WebSocket debugger URL
|
|
const WebSocket = require('ws');
|
|
const ws = new WebSocket(targetTab.webSocketDebuggerUrl);
|
|
|
|
ws.on('open', () => {
|
|
console.log('Connected to Chrome DevTools');
|
|
|
|
// Send Runtime.evaluate command to execute the script
|
|
ws.send(JSON.stringify({
|
|
id: 1,
|
|
method: 'Runtime.evaluate',
|
|
params: {
|
|
expression: scriptContent,
|
|
returnByValue: true
|
|
}
|
|
}));
|
|
});
|
|
|
|
ws.on('message', (data) => {
|
|
const message = JSON.parse(data);
|
|
|
|
if (message.id === 1) {
|
|
if (message.result.exceptionDetails) {
|
|
console.error('Script execution error:', message.result.exceptionDetails);
|
|
} else {
|
|
console.log('Script executed successfully');
|
|
if (message.result.result.value !== undefined) {
|
|
console.log('Result:', message.result.result.value);
|
|
}
|
|
}
|
|
ws.close();
|
|
process.exit(0);
|
|
}
|
|
});
|
|
|
|
ws.on('error', (error) => {
|
|
console.error('WebSocket error:', error);
|
|
process.exit(1);
|
|
});
|
|
|
|
} catch (error) {
|
|
if (error.code === 'ECONNREFUSED') {
|
|
console.error('Could not connect to Chrome. Make sure Chrome is running with:');
|
|
console.error('chrome.exe --remote-debugging-port=9222');
|
|
} else {
|
|
console.error('Error:', error.message);
|
|
}
|
|
process.exit(1);
|
|
}
|
|
}
|
|
|
|
const scriptFile = process.argv[2];
|
|
|
|
if (!scriptFile) {
|
|
console.error('Usage: node run-script.js <script-file>');
|
|
process.exit(1);
|
|
}
|
|
|
|
if (!fs.existsSync(scriptFile)) {
|
|
console.error(`Script file not found: ${scriptFile}`);
|
|
process.exit(1);
|
|
}
|
|
|
|
executeScriptOnCurrentTab(scriptFile);
|
|
|