如何实现在Google Chrome多标签页中同步向两个网站发送信息?
实现Chrome多标签页输入内容同步的方案
一、Chrome扩展(最推荐的原生方案)
Chrome扩展可以直接访问标签页DOM,通过chrome.tabs和chrome.storageAPI实现跨标签页通信,是最稳定、适配性最好的方案:
核心逻辑
- 监听site1输入框的内容变化,将实时值存入Chrome的
chrome.storage.local(该存储区域支持跨标签页共享) - 在site2的标签页中监听存储数据的变化,自动将同步值填充到对应输入框
关键代码示例
内容脚本(注入到两个目标网站)
// 针对site1:监听输入框,同步内容到存储 if (window.location.host.includes('site1-domain')) { const input = document.querySelector('#site1-input-selector'); // 替换为site1输入框的实际选择器 input.addEventListener('input', (e) => { chrome.storage.local.set({ syncInputText: e.target.value }); }); } // 针对site2:监听存储变化,同步内容到输入框 if (window.location.host.includes('site2-domain')) { // 初始化时同步已有值 chrome.storage.local.get('syncInputText', (data) => { if (data.syncInputText) { const input = document.querySelector('#site2-input-selector'); // 替换为site2输入框的实际选择器 input.value = data.syncInputText; } }); // 实时监听存储更新 chrome.storage.onChanged.addListener((changes) => { if (changes.syncInputText) { const input = document.querySelector('#site2-input-selector'); input.value = changes.syncInputText.newValue; } }); }
扩展清单文件(manifest.json)
{ "manifest_version": 3, "name": "跨站输入同步工具", "version": "1.0", "permissions": ["storage", "tabs"], "content_scripts": [ { "matches": ["https://site1-domain.com/*", "https://site2-domain.com/*"], // 替换为两个网站的实际域名 "js": ["content.js"] } ] }
将上述代码整理成扩展包安装到Chrome,即可实现全自动同步,无需手动干预。
二、低门槛替代方案:Tampermonkey油猴脚本
无需打包扩展,直接用用户脚本注入到目标网站,利用油猴的跨标签页存储API实现同步:
// ==UserScript== // @name 跨站输入内容同步 // @match https://site1-domain.com/* // @match https://site2-domain.com/* // @grant GM_setValue // @grant GM_addValueChangeListener // @grant GM_getValue // ==/UserScript== if (window.location.host.includes('site1-domain')) { const input = document.querySelector('#site1-input-selector'); input.addEventListener('input', (e) => { GM_setValue('syncText', e.target.value); }); } else if (window.location.host.includes('site2-domain')) { // 监听存储变化实时同步 GM_addValueChangeListener('syncText', (key, oldVal, newVal) => { const input = document.querySelector('#site2-input-selector'); input.value = newVal; }); // 初始化同步已有内容 const currentVal = GM_getValue('syncText'); if (currentVal) { document.querySelector('#site2-input-selector').value = currentVal; } }
只需在Tampermonkey中新建脚本并粘贴上述代码,替换对应选择器和域名即可使用,门槛更低。
三、不推荐的方案:机器人脚本/模拟光标
你提到的复制鼠标光标、机器人脚本(如AutoHotkey)属于模拟用户物理操作,存在诸多弊端:
- 容易触发网站的反爬/反自动化机制,导致操作被拦截
- 必须保持目标窗口前置,无法后台运行
- 依赖页面布局,网站UI改动后脚本直接失效
因此不建议采用这类方案。
总结
优先选择Chrome扩展或Tampermonkey脚本,二者均基于浏览器原生能力实现,稳定、无副作用,完全满足自动同步的需求。
内容的提问来源于stack exchange,提问作者Fenix Falcao Viana Calixto
相关产品推荐
相关产品推荐

