You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chrome扩展开发需求:基于首个标签页自动同步第二个标签页导航

可以通过Chrome Extension实现该功能

完全可以,核心思路是监听目标网站的页面标题变化、提取客户ID,再自动控制第二个标签页的导航地址。以下是具体实现方案:

核心实现步骤

  • 监听标题变化:在第一个网站注入内容脚本,监听页面标题的更新事件
  • 提取客户ID:通过正则表达式从更新后的标题中匹配出客户ID
  • 控制标签页导航:通过扩展的背景脚本接收ID,查找或创建第二个标签页并跳转到带ID的目标地址

代码示例

1. manifest.json(扩展配置文件)

{
  "manifest_version": 3,
  "name": "客户页面同步工具",
  "version": "1.0",
  "permissions": ["tabs"],
  "host_permissions": [
    "*://第一个网站域名/*",
    "*://第二个网站域名/*"
  ],
  "content_scripts": [
    {
      "matches": ["*://第一个网站域名/*"],
      "js": ["content.js"]
    }
  ],
  "background": {
    "service_worker": "background.js"
  }
}

2. content.js(注入第一个网站的内容脚本)

// 监听页面标题变化
const observer = new MutationObserver((mutations) => {
  mutations.forEach((mutation) => {
    if (mutation.type === 'childList' && mutation.target === document.querySelector('title')) {
      const newTitle = document.title;
      // 请根据实际标题格式调整正则表达式,比如标题格式为"客户ID:123 - 张三 - 目标信息"
      const idMatch = newTitle.match(/客户ID:(\d+)/);
      if (idMatch && idMatch[1]) {
        const customerId = idMatch[1];
        // 向背景脚本发送客户ID
        chrome.runtime.sendMessage({ type: 'UPDATE_CUSTOMER_ID', id: customerId });
      }
    }
  });
});

observer.observe(document.head, { childList: true, subtree: true });

3. background.js(后台服务脚本)

// 预设第二个网站的基础地址
const SECOND_SITE_BASE_URL = 'https://第二个网站域名/客户详情?id=';

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'UPDATE_CUSTOMER_ID') {
    const targetUrl = SECOND_SITE_BASE_URL + message.id;
    // 查找已打开的第二个网站标签页
    chrome.tabs.query({ url: '*://第二个网站域名/*' }, (tabs) => {
      if (tabs.length > 0) {
        // 更新已有标签页的地址
        chrome.tabs.update(tabs[0].id, { url: targetUrl });
      } else {
        // 创建新标签页并导航
        chrome.tabs.create({ url: targetUrl });
      }
    });
  }
});

关键注意事项

  • 正则匹配调整:务必根据第一个网站的实际标题格式修改content.js中的正则表达式,确保能准确提取客户ID
  • 权限配置:host_permissions中要填写两个网站的实际域名,避免权限不足
  • 标签页识别:如果第二个网站的URL格式有变化,需要调整chrome.tabs.query中的匹配规则

内容的提问来源于stack exchange,提问作者Kapil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 18:04:59