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

如何在Chrome扩展的content scripts中访问扩展本地存储数据

Chrome扩展content script读取扩展存储解决方案

核心原因

你在popup中使用的localStorage属于popup页面独立上下文的存储,和运行在网页上下文的content script(login.js)的存储完全隔离,所以直接调用localStorage只能拿到当前网站的存储数据,无法读取扩展侧的存储内容。
你已经在manifest.json中申请了storage权限,直接使用Chrome官方提供的chrome.storage.localAPI即可实现扩展全上下文(popup、background、content script)的数据共享。

第一步:修改popup.js存储逻辑

将原来使用localStorage存储凭据的逻辑替换为chrome.storage.local存储:

// 修改myAction函数内的存储逻辑
function myAction(username, password) {
  if (username.value && password.value) {
    let user = [{ username: username.value, password: password.value }];
    // 替换原有localStorage.setItem
    chrome.storage.local.set({ users: user }, () => {
      // 存储完成后再触发通知,确保数据落地
      chrome.notifications.create("SaveData", {
        type: "basic",
        iconUrl: "images/logo64.png",
        title: "Successful!",
        message: "Your data successfully saved in Database",
        priority: 2,
      });
    });
  } else {
    alert("Please, enter your user credentials");
  }
}

第二步:编写login.js读取逻辑

content script可以直接调用chrome.storage.local读取存储的凭据,完成自动填充登录:

// 等待页面加载完成后执行操作
window.addEventListener('load', () => {
  // 读取扩展存储的用户凭据
  chrome.storage.local.get('users', (result) => {
    // 未存储凭据直接返回
    if (!result.users || result.users.length === 0) return;
    const { username, password } = result.users[0];
    
    // 以下选择器需要替换为你目标登录页的实际元素选择器
    // 填充用户名
    document.querySelector('input[name="username"]').value = username;
    // 填充密码
    document.querySelector('input[name="password"]').value = password;
    // 触发登录按钮点击
    document.querySelector('button[type="submit"]').click();
  });
});

补充注意事项

  • manifest.json中content_scripts的matches字段需要替换为你实际要适配的目标网站登录页地址,避免在无关页面触发逻辑
  • 如果目标网站登录框是懒加载渲染的,需要加定时器或者DOM监听逻辑确保元素存在后再执行填充操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 08:45:05