更新
从 Chrome 20 开始,您现在可以使用 Storage api.....
http://code.google.com/chrome/extensions/storage.html
老办法
我所做的是创建一个 iframe,该 iframe 指向我的扩展程序中的一个页面,该页面具有一个脚本,该脚本从本地存储中获取我需要的设置,然后在一条消息中将其发送给它的父级,然后内容脚本会获取.....好吧这是一个废话解释,代码说得更好;).......
内容脚本
// create the iframe for our page that sends the settings
var el = document.createElement("iframe");
el.setAttribute('src', chrome.extension.getURL("gimmeSettings.html"));
el.style.visibility="hidden";
document.body.appendChild(el);
// create the listner that listens for a message from our page that sends the settings
window.addEventListener("message", receiveSettings, false);
// function that gets called when we recieve a message from the page that sends the settings
function receiveSettings(event) {
//check to make sure the message came from our page
if (event.origin !== "chrome-extension://"+chrome.i18n.getMessage("@@extension_id")) return;
//message came from our extension, do stuff with it
console.debug(event.data);
// clean up
window.removeEventListener("message", receiveSettings, false);
el.parentNode.removeChild(el);
}
gimmeSettings.html 的 JS
// post the message with our settings
parent.postMessage( localStorage.getItem("testing"), "*" );
Options.html 的 JS
localStorage.setItem("testing","bleh");
清单
{
"name": "Getting at an extensions local storage from a content script",
"description" : "Getting at an extensions local storage from a content script. Be aware that other pages/extensions can use this to get at your settings, but not change them...so dont include sensitvie data.",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js" : ["myscript.js"],
"run_at":"document_idle"
}
],
"permissions": [
"tabs", "<all_urls>"
],
"manifest_version": 2,
"web_accessible_resources": [
"gimmeSettings.html"
],
"options_page": "options.html",
"version":"1.0"
}
注意事项....
其他页面和扩展程序可以很容易地使用它来从您的扩展程序中获取设置,所以不要使用这种方法使用任何敏感数据。
据我所知,他们无法通过该页面更改您的设置,如果有人知道不同,请解释。
我使用清单版本 2 并将页面 gimmeSettings 设置为可访问。如果您不知道清单版本 2 的差异添加,您真的应该阅读它....http://code.google.com/chrome/extensions/trunk/manifestVersion.html
如果你想要一个可行的例子,那就去这里.....
http://forum.valorsolo.com/viewtopic.php?f=36&t=375