6

如何写入不同域的本地存储。这个想法是我需要我的 chrome 扩展在本地存储中写一些东西,当用户访问相关网站时,站点站点可以读取本地存储的内容。我正在尝试在用户的个人数据之间进行同步,而不必将它们存储在服务器中。

4

2 回答 2

8

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.

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

  2. 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);
    });
});
于 2013-03-08T10:45:51.190 回答
2

由于跨域限制,我认为唯一的解决方案是通过脚本注入。

var s = document.createElement('script');
s.src = chrome.extension.getURL("script.js");
s.onload = function() {
    this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s);

将文件添加script.js到访问其他站点 localStorage 的扩展程序中,您必须script.js在清单文件中添加到“web_accessible_resources”。

请注意,脚本在完全加载后会自动删除,因此请确保您要执行的代码包含在自可执行函数中。

于 2013-03-08T08:39:57.820 回答