[英]Chrome extension: store data on background
我希望能够在后台(在我的扩展名上)存储数据,以便可以在多个域之间访问此数据。
我在做什么
内容脚本
function setItem(name, data) {
chrome.extension.sendMessage({ command: 'setItem', name: name, data: data });
}
function getItem(name) {
chrome.extension.sendMessage({ command: 'getItem', name: name }, function(response) {
return response;
});
}
background-script.js
Storage.prototype.setObject = function(key, value) {
this.setItem(key, JSON.stringify(value));
}
Storage.prototype.getObject = function(key) {
var value = this.getItem(key);
return value && JSON.parse(value);
}
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
switch (request.command) {
case 'setItem':
localStorage.setObject(request.name, request.data);
return;
case 'getItem':
sendResponse(localStorage.getObject(request.name));
return;
}
});
但是没有成功,因为我无法从getItem的回调内部返回。
我确实在function(response) { }
回调中获取了数据,但我无法将其作为getItem的返回返回。
我应该怎么做?
这个2012年的问题是为了提供最新答案而提出的。 好吧..
现在正确的答案是使用chrome.storage
API 。 它是扩展页面和内容脚本均可访问的API,并且提供异步存储。 它需要"storage"
权限,但是此权限不会生成警告。
// Setting
chrome.storage.local.set({key: data}, function() {
if(chrome.runtime.lastError) {
console.error(
"Error setting " + key + " to " + JSON.stringify(data) +
": " + chrome.runtime.lastError.message
);
}
});
// Getting
chrome.storage.local.get("key", function(data) {
// Do something with data.key
});
另请参见文档的“ 示例”部分。
请注意,无论哪种情况(此方法或后台消息传递方法),都无法使函数getData
返回结果,因为调用是异步的。
一些提示和技巧:
您可以通过传递对象或数组作为查询来一次设置或获取多个值。 您可以通过传递null
查询来读取所有值。
如果没有为键存储任何值,则可以通过传递类似{key: defaultValue}
的查询来为get()
操作提供默认值。
您可以通过chrome.storage.onChanged
事件通知存储的所有更改。
chrome.storage.local
遵守"unlimitedStorage"
权限。
如果为扩展程序启用了Chrome同步,则chrome.storage.sync
会将值传播到登录到同一Google帐户的所有配置文件。 但是,请记住配额 。
如果您绝对需要同步访问,则可以使用由chrome.storage
支持的本地缓存来伪造它。 但是,存在一些限制:在同步代码块中,不会使用其他页面的更改来更新缓存,并且您需要异步读取一次值以填充缓存。
Content.js
var someVar = "hey hey!";
chrome.extension.sendRequest({method: "fromContentScript",greeting: someVar}, function(response) {
console.log(response.data); // response back from BG
if(response.who == 'bg'){ // checks if the response is from BG
//Something happened ...
}
var responseFromBg = response.data; // the response incase we need to use the message sent back... in this case should be 'hey yourself'
});
Background.js
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
// From content script.
if (sender.tab) {
if (request.method == "fromContentScript"){
localStorage.setItem("welcome-message",request.greeting); // in this case there will now be a localStorage variable called 'welcome-message' set with the value of 'hey hey!'. This will be viewable in the chrome:extensions page, click on the 'background.html / generated background.html' then view the 'Development Tools' or in Windows hit 'CTRL + SHIFT + I' and look at the 'LocalStorage' tab...
sendResponse({who: "bg",data: "hey yourself"}); // this is the response sent back, 'who' tells the content page where is responding, so it can do something with the response if needed.
}else{
sendResponse({}); // snub them.
}
}
});
Manifest.json // //如果这是您遇到的明显问题...这是我的大部分。
{
"name": "Name here",
"version": "1",
"manifest_version": 2,
"description": "Enter desc here.",
"browser_action": {
"default_icon": "img/icon16.png",
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"]
},
"permissions": [
"tabs", "*://*/*"
],
"icons": { "16": "img/icon16.png",
"48": "img/icon48.png",
"128": "img/icon128.png" },
"content_scripts": [
{
"matches": ["*://*/*"],
"js": ["js/jquery-1.7.2.min.js","content_script.js"],
"run_at": "document_end"
}
]
}
本来会以您为榜样,但我今早很着急。 我试图尽可能详细地解释所有变量-对不起:(
background-script.js:
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
switch (request.command) {
case 'setItem':
localStorage[request.name] = JSON.stringify(request.data));
return;
case 'getItem':
var retValue;
if (typeof(localStorage[request.name]) === 'string') {
retValue = JSON.parse(localStorage[request.name]);
}
sendResponse(retValue);
return;
case 'deleteItem':
if (typeof localStorage[request.name] !== 'undefined') {
delete localStorage[request.name];
}
return;
}
});
如果键不在localStorage中,则getItem将返回undefined
。 与其按照定义方法定义getItem
函数,不应该使用回调将消息发送到后台,然后在调用回调时对值进行处理。 您不能从函数getItem
返回值,但是可以在调用回调函数时使用该值:
function getItem(name, callback) {
chrome.extension.sendMessage({command: 'getItem', name: name}, function(response) {
if (typeof(callback) === "function") {
callback(response);
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.