Search code examples
google-chromegoogle-chrome-extensionlocal-storage

Can I get access to localStorage of site from chrome extension?


My chrome extension has two state: 1. Some site has auth data in localStorage (another domain), so I have to show main window. 2. There is no auth data, so I have to show window with login and password form.

In order to define if auth data is presented, I would like to check his localStorage, but it looks like it's impossible.

However, chrome.storage.local.get and chrome.storage.local.setworks perfectly for localStorage of extension.

Or is there approach to do this - get access to localStorage of another site ?


Solution

  • 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.

    I'm using chrome-extension-async for async/await support.

    For instance in 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
        }
    });