Chrome浏览页面合规数据持久化存储方案优化咨询
优化现有方案(避免打开新标签)
核心是用异步HTTP请求替代window.open,既不会弹出新标签,还能处理请求结果、避免数据传输的长度限制问题。
步骤1:修改TamperMonkey脚本
把window.open替换成fetch(或TamperMonkey自带的GM_xmlhttpRequest,解决跨域问题更方便),同时对数据做URL编码防止特殊字符出错:
// ==UserScript== // @name CheckData // @namespace http://tampermonkey.net/ // @version 0.2 // @description 提取页面数据并后台保存,不弹出新标签 // @author CB // @match *://*/* // 按需修改匹配规则,对应你日常浏览的页面 // @grant GM_xmlhttpRequest // 使用GM请求需添加该权限 // ==/UserScript== (function() { // 用load事件替代setTimeout,更精准等待页面加载完成 window.addEventListener('load', delayedStuff); function delayedStuff() { const dataFound = document.querySelector("#mystuff > div.mydiv")?.textContent; if (!dataFound) return; if (dataFollowsRule(dataFound)) { // 优先用GM_xmlhttpRequest,无需处理跨域 GM_xmlhttpRequest({ method: "POST", url: "http://localhost:8000/savedata.php", data: `data=${encodeURIComponent(dataFound)}`, headers: { "Content-Type": "application/x-www-form-urlencoded" }, onload: function(response) { console.log('数据保存成功:', response.responseText); }, onerror: function(error) { console.error('保存失败:', error); } }); // 若无需处理跨域,也可使用原生fetch // fetch('http://localhost:8000/savedata.php', { // method: 'POST', // headers: { // 'Content-Type': 'application/x-www-form-urlencoded', // }, // body: `data=${encodeURIComponent(dataFound)}` // }) // .then(res => res.text()) // .then(msg => console.log(msg)) // .catch(err => console.error(err)); } } // 实现你的规则判断逻辑 function dataFollowsRule(data) { // 示例:判断数据是否包含目标关键词 return data.includes('目标关键词'); } })();
步骤2:修改savedata.php支持POST请求
添加CORS头(如果脚本运行在非localhost域名的页面),同时用预处理语句防止SQL注入:
<?php // 允许跨域请求(适配非localhost页面的脚本) header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Methods: POST, GET"); header("Access-Control-Allow-Headers: Content-Type"); // 接收POST数据(兼容GET降级) $data = $_POST['data'] ?? $_GET['data'] ?? ''; if (empty($data)) { echo "无有效数据"; exit; } // 连接数据库(示例为MySQL) $servername = "localhost"; $username = "你的数据库用户名"; $password = "你的数据库密码"; $dbname = "你的数据库名"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } // 预处理语句防止SQL注入 $stmt = $conn->prepare("INSERT INTO saved_data (content, created_at) VALUES (?, NOW())"); $stmt->bind_param("s", $data); if ($stmt->execute()) { echo "数据保存成功"; } else { echo "保存失败: " . $stmt->error; } $stmt->close(); $conn->close(); ?>
替代方案:使用Chrome扩展
如果用户脚本的权限受限或跨域问题难以处理,Chrome扩展是更稳定的选择,拥有更可靠的后台请求能力:
核心逻辑
content script注入到浏览的页面,检测并提取符合规则的数据- 通过
chrome.runtime.sendMessage将数据传递给后台脚本 - 后台脚本异步发送请求到localhost服务器存储数据
关键代码示例
content.js(注入页面的脚本)
window.addEventListener('load', () => { const dataFound = document.querySelector("#mystuff > div.mydiv")?.textContent; if (!dataFound || !dataFollowsRule(dataFound)) return; chrome.runtime.sendMessage({action: 'saveData', data: dataFound}); }); function dataFollowsRule(data) { return data.includes('目标关键词'); }
background.js(后台服务脚本)
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => { if (request.action === 'saveData') { fetch('http://localhost:8000/savedata.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `data=${encodeURIComponent(request.data)}` }) .then(res => res.text()) .then(msg => console.log(msg)) .catch(err => console.error(err)); } });
manifest.json(扩展配置文件)
{ "manifest_version": 3, "name": "数据采集工具", "version": "1.0", "content_scripts": [ { "matches": ["*://*/*"], "js": ["content.js"] } ], "background": { "service_worker": "background.js" }, "permissions": ["activeTab"] }
数据导出方案
在localhost服务器添加exportdata.php页面,可一键导出数据库中的数据为CSV(方便Excel打开)或JSON格式:
<?php header("Access-Control-Allow-Origin: *"); $servername = "localhost"; $username = "你的数据库用户名"; $password = "你的数据库密码"; $dbname = "你的数据库名"; $conn = new mysqli($servername, $username, $password, $dbname); if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } $sql = "SELECT * FROM saved_data ORDER BY created_at DESC"; $result = $conn->query($sql); // 导出为CSV格式 header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename="saved_data.csv"'); $output = fopen('php://output', 'w'); // 写入表头 fputcsv($output, ['ID', '内容', '保存时间']); // 写入数据行 while ($row = $result->fetch_assoc()) { fputcsv($output, [$row['id'], $row['content'], $row['created_at']]); } fclose($output); $conn->close(); ?>
内容的提问来源于stack exchange,提问作者carlo.borreo
相关产品推荐
相关产品推荐

