如何通过HTML按钮触发Node.js命令执行Selenium登录脚本,实现校园门户PWA的自动化操作
Hey there! Welcome to Stack Overflow—great first question 😊
Let's break down what you need to do here: your PWA runs in the browser, which can't directly execute Node.js commands or system scripts (browser security restrictions prevent that). So you'll need a small backend service to act as a middleman: when your PWA's button is clicked, it sends a request to this backend, and the backend runs your Selenium script for you.
Here's a step-by-step implementation:
1. Set up a simple Express backend
This backend will expose an API endpoint that triggers your Selenium script when called.
First, install required dependencies:
npm install express cors
Create a server.js file with this code:
const express = require('express'); const { exec } = require('child_process'); const cors = require('cors'); const app = express(); // Restrict CORS to your PWA's origin (replace with your actual PWA URL) app.use(cors({ origin: 'http://localhost:5173' })); app.use(express.json()); // Add security: use an API key to prevent unauthorized calls const VALID_API_KEY = 'your-secure-random-key-here'; // API endpoint to run the Selenium script app.post('/trigger-selenium', (req, res) => { const apiKey = req.headers['x-api-key']; if (!apiKey || apiKey !== VALID_API_KEY) { return res.status(403).json({ error: 'Unauthorized: Invalid API key' }); } // Run your Selenium script (update the path to match your file location) exec('node ./path/to/your-selenium-script.js', (error, stdout, stderr) => { if (error) { console.error(`Script failed: ${error.message}`); return res.status(500).json({ error: `Script failed: ${error.message}` }); } if (stderr) { console.error(`Script errors: ${stderr}`); return res.status(500).json({ error: `Script generated errors: ${stderr}` }); } res.json({ message: 'Selenium script executed successfully!', output: stdout }); }); }); const PORT = 3001; app.listen(PORT, () => { console.log(`Backend running at http://localhost:${PORT}`); });
2. Update your Selenium script for server/headless use
To avoid popping up a Firefox window (ideal for server environments), switch to headless mode. Also, always clean up the driver after execution:
const { Builder, By, Key } = require("selenium-webdriver"); const firefox = require('selenium-webdriver/firefox'); async function example() { let driver; try { const options = new firefox.Options(); options.headless(); // Run Firefox without a visible window driver = await new Builder() .forBrowser("firefox") .setFirefoxOptions(options) .build(); await driver.get("https://login.gitam.edu/Login.aspx"); await driver.findElement(By.name("txtusername")).sendKeys("0116"); await driver.findElement(By.name("password")).sendKeys("password", Key.RETURN); console.log("Login action completed successfully"); } catch (err) { console.error("Error during script execution:", err); throw err; } finally { if (driver) await driver.quit(); // Always close the driver to free resources } } example();
3. Add the button to your PWA UI
Add a button and a click handler that sends a request to your backend:
<button id="runLoginScript">Run Portal Login</button> <script> document.getElementById('runLoginScript').addEventListener('click', async () => { const button = event.target; button.disabled = true; button.textContent = 'Running...'; try { const response = await fetch('http://localhost:3001/trigger-selenium', { method: 'POST', headers: { 'Content-Type': 'application/json', 'x-api-key': 'your-secure-random-key-here' // Match the key in your backend } }); if (!response.ok) throw new Error('Request failed'); const result = await response.json(); alert(result.message); } catch (err) { console.error('Error:', err); alert(`Failed to run script: ${err.message}`); } finally { button.disabled = false; button.textContent = 'Run Portal Login'; } }); </script>
Critical Notes
- Security: Never skip the API key validation, and don't expose this backend publicly without proper authentication. Executing system commands via an API is a major security risk if not protected.
- Credentials: Don't hardcode usernames/passwords in your script! Use environment variables or have the PWA send user input to the backend (with proper encryption).
- Environment: Ensure your backend server has Firefox and Geckodriver installed (same setup as when you ran the script locally).
内容的提问来源于stack exchange,提问作者saipranav addanki

