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

如何通过Chrome扩展从sync storage修改URL?多账号authuser参数配置

解决方案:自动设置谷歌服务URL的authuser默认参数

一、代码存放位置

核心逻辑放在**Service Worker(后台脚本)**即可,不需要content script。原因很简单:content script只能在页面加载完成后运行,没法提前拦截初始请求(比如手动输入URL、外部跳转链接),而Service Worker可以在请求发起阶段直接处理,保证体验流畅。

二、API选择对比与最优方案

直接对比你列出的选项:

  • window.location:只能在页面加载后修改URL,会触发二次跳转,体验差,完全没法处理初始请求,直接排除。
  • chrome.tabs:需要监听标签页创建、更新等多个事件,只能修改标签页的URL,没法覆盖页面内所有跳转场景,复杂度高,不推荐。
  • declarativeNetRequest:Chrome官方推荐的现代API,性能优异,不需要持续监听,通过规则匹配请求并自动修改URL,完美覆盖手动输入、外部链接、页面内跳转等所有场景,是最优选择。
  • chrome.webRequest:旧版API,功能全但资源占用高,现在已经被declarativeNetRequest替代,没必要再用。

具体实现步骤

1. 配置manifest.json

需要声明必要的权限和后台脚本:

{
  "manifest_version": 3,
  "name": "AuthUser 默认设置",
  "version": "1.0",
  "permissions": ["declarativeNetRequest", "storage"],
  "host_permissions": ["*://*.google.com/*"],
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_popup": "popup.html"
  }
}

2. 后台脚本(background.js)逻辑

读取用户设置的authuser值,动态生成拦截规则:

// 获取用户设置的authuser值,默认0
async function getAuthUser() {
  const result = await chrome.storage.sync.get('authuser');
  return result.authuser || '0';
}

// 更新请求拦截规则
async function updateRules() {
  const authUser = await getAuthUser();
  // 先清除旧规则,再添加新规则
  await chrome.declarativeNetRequest.updateDynamicRules({
    removeRuleIds: [1],
    addRules: [
      {
        id: 1,
        priority: 1,
        action: {
          type: 'redirect',
          redirect: {
            transform: {
              queryTransform: {
                addOrReplaceParams: [{key: 'authuser', value: authUser}]
              }
            }
          }
        },
        condition: {
          urlFilter: '*://*.google.com/*',
          resourceTypes: ['main_frame', 'sub_frame']
        }
      }
    ]
  });
}

// 初始化时加载规则
updateRules();
// 监听存储变化,实时更新规则
chrome.storage.onChanged.addListener((changes) => {
  if (changes.authuser) updateRules();
});

3. Popup部分(沿用你现有基础)

只需要把输入的authuser值保存到storage.sync即可:

// popup.js
document.addEventListener('DOMContentLoaded', async () => {
  const saved = await chrome.storage.sync.get('authuser');
  if (saved.authuser) {
    document.getElementById('authuser-input').value = saved.authuser;
  }
});

document.getElementById('save-btn').addEventListener('click', async () => {
  const inputVal = document.getElementById('authuser-input').value.trim();
  if (inputVal) {
    await chrome.storage.sync.set({authuser: inputVal});
    alert('设置已保存');
  }
});

补充说明

  • 可以根据需求调整host_permissions,比如只针对邮箱、网盘等特定谷歌服务(如*://mail.google.com/*)
  • declarativeNetRequest规则由Chrome内核高效处理,不会像旧版webRequest那样占用过多后台资源

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 01:05:27