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

如何在Chrome扩展中获取当前标签页网页的localStorage值

如何获取当前标签页网页的localStorage值?

嗨,我懂你现在的困惑啦——你搞混了Chrome扩展的chrome.storage.local和网页自身的localStorage!前者是扩展专属的存储区域,和当前标签页网页的localStorage完全不互通,所以用它自然拿不到网页里的granted.selected值。

要拿到网页的localStorage,得用「向目标标签页注入脚本」的方式,因为只有在网页的上下文里,才能直接访问它的localStorage。下面是具体的步骤:

1. 先给扩展配置必要权限

打开你的manifest.json(扩展的核心配置文件),确保添加了activeTab和scripting权限(以Manifest V3为例,现在主流都是这个版本):

{
  "manifest_version": 3,
  "name": "你的扩展名称",
  "version": "1.0",
  "permissions": ["activeTab", "scripting"],
  "action": {
    "default_popup": "popup.html" // 如果你的扩展有弹窗的话
  }
}
  • activeTab:允许扩展临时访问当前活跃的标签页
  • scripting:允许扩展向标签页注入脚本

2. 编写点击按钮后的逻辑

假设你的扩展点击按钮后会弹出popup,那就在popup.js里写如下代码:

// 给弹窗里的按钮绑定点击事件(如果是直接点击扩展图标触发,就用chrome.action.onClicked.addListener)
document.getElementById('getLocalBtn').addEventListener('click', async () => {
  try {
    // 第一步:获取当前活跃的标签页
    const [currentTab] = await chrome.tabs.query({ active: true, currentWindow: true });
    
    // 第二步:向该标签页注入脚本,在网页上下文里获取localStorage
    const scriptResult = await chrome.scripting.executeScript({
      target: { tabId: currentTab.id },
      // 这个函数会在网页的环境中执行,所以能直接访问网页的localStorage
      func: () => localStorage.getItem('granted.selected')
    });
    
    // 第三步:拿到返回值并处理
    const targetValue = scriptResult[0].result;
    console.log('Value currently is ' + targetValue);
    // 也可以把值显示在弹窗里,比如:
    document.getElementById('resultText').textContent = `当前值:${targetValue || '未找到该键'}`;
  } catch (err) {
    console.error('获取失败:', err);
  }
});

关键说明

  • chrome.scripting.executeScript是核心:它把我们写的func函数注入到目标网页里执行,这个函数运行在网页的上下文环境中,所以能直接调用网页的localStorage API。
  • 如果你的扩展没有popup,是点击图标直接触发逻辑,那可以用chrome.action.onClicked.addListener替代弹窗按钮的事件绑定,逻辑是一样的。

额外注意事项

  • 如果目标网页是chrome://开头的系统页面,或者扩展自身的页面,可能无法注入脚本(浏览器限制)。
  • 部分网页有严格的内容安全策略(CSP),可能会阻止脚本注入,但普通网页一般不会有这个问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 12:47:31