且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-05 23:24:22

是的,您可以在页面上执行脚本来访问本地存储.您可以通过两种不同的方法来执行此操作,包括内容脚本或注入脚本.

Yes, you can execute a script on the page to access the local storage. There are a couple of different ways you can do this, including content scripts or injected scripts.

我正在使用 chrome-extension-async 来获得async/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
    }
});