我可以从 Chrome 扩展程序访问站点的 localStorage 吗?

Eug*_*gun 7 google-chrome local-storage google-chrome-extension

我的 chrome 扩展有两种状态: 1. 某些站点在 localStorage(另一个域)中有身份验证数据,所以我必须显示主窗口。2.没有身份验证数据,所以我必须显示带有登录名和密码表单的窗口。

为了定义是否提供身份验证数据,我想检查他的 localStorage,但看起来不可能。

但是,chrome.storage.local.get并且chrome.storage.local.set非常适合扩展的 localStorage。

或者有没有办法做到这一点 - 访问另一个站点的 localStorage ?

Kei*_*ith 6

是的,您可以在页面上执行脚本来访问本地存储。有几种不同的方法可以做到这一点,包括内容脚本或注入脚本。

我使用chrome-extension-asyncasync/await支持。

例如在 popup.js

document.addEventListener('DOMContentLoaded', async () => {
    try {
        const key = "foobar"

        // Get the current tab
        const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
        const tab = tabs[0]; 

        // Execute script in the current tab
        const fromPageLocalStore = await chrome.tabs.executeScript(tab.id, { code: `localStorage['${key}']` });

        // Store the result  
        await chrome.storage.local.set({[key]:fromPageLocalStore[0]});
    } 
    catch(err) {
        // Log exceptions
    }
});
Run Code Online (Sandbox Code Playgroud)

  • @EugeneShmorgun 即使没有打开选项卡,您是否也能够读取域的本地存储?基思的回答当然有道理,但只是在一定程度上。浏览器中的本地存储被创建为存在于选项卡上下文之外,但存在于域上下文中,并且在选项卡关闭后仍然存在。这就是它的目的。这就是为什么能够在不打开该域的选项卡的情况下读取域的本地存储(您在清单中拥有权限)的原因是非常有意义的。 (4认同)
  • 只需更改此行 const fromPageLocalStore = wait chrome.tabs.executeScript(tab.id, { code: `localStorage['${key}']` }); const fromPageLocalStore =等待 chrome.scripting.executeScript({ target: { tabId: tab.id }, function: () => localStorage[key] }); (2认同)