Chrome extension - Write to local storage of a different domain

google-chrome-extension, javascript, local-storage

Solution

Content scripts have direct acccess to a page's localStorage.

If you want to store a value for a specific domain, just open a window or frame, then write to the window/page's local storage.

- Pick your favorite option to activate the page:

- `chrome.tabs.create` to create an inactive tab, perhaps in the non-active window found by using `chrome.tabs.query`.

- The experimental `offscreenTabs` API (experimental, so not ready for use in production). See some of the examples I posted on SO.

- Create an IFrame and insert it in the current page.

- `window.open` (not recommended...)

When you decide to open a page, pick one which is light-weight. `/robots.txt` is usually a good choice: It exists on most sites, and it is a plain text file.

- Activate the content script for the page. You can either use the manifest file and make use of the messaging APIs, or add a callback to the `chrome.tabs.create` method which programatically inserts a content script (`chrome.tabs.executeScript`).

Here's a simple example. It requires the `tabs` API because I'm using `chrome.tabs.executeScript`. Furthermore, the origin you want to access should also be added to the permissions list.

chrome.tabs.create({
    active: false,
    url: 'http://stackoveflow.com/robots.txt'
}, function(tab) {
    chrome.tabs.executeScript(tab.id, {
        code: 'localStorage.setItem("key", "value");'
    }, function() {
        chrome.tabs.remove(tab.id);
    });
});

Update (2022)

Since `Manifest version 3` the `chrome.tabs.executeScript` API was replaced with the `chrome.scripting.executeScript` API, hence the code above can be changed to be like this:

function saveToLocalStorage() {
    localStorage.setItem("key", "value");
}

chrome.tabs.create({
    active: false,
    url: 'http://stackoveflow.com/robots.txt'
}, function(tab) {
    chrome.scripting.executeScript({
        target: {tabId: tab.id},
        func: saveToLocalStorage,
    }, function() {
        chrome.tabs.remove(tab.id);
    });
});

And please note, you need to add the `"scripting"` permission to your `manifest.json` file in order to use this API.

Problem

How can I write to a local storage of a different domain. The idea is that I need my chrome extension to write something in the local storage and when the user visits the associated website, site site can read the contents of the local storage. I am trying to do a sync between the user's personal data without having to store them in the server.

Original source