Chrome扩展程序:将数据存储在后台
Chrome extension: store data on background
我希望能够在后台(在我的扩展上)存储数据,以便我可以在多个域之间访问这些数据。
我在做什么:
内容脚本.js
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;
});
}
后台脚本.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
支持的本地缓存来伪造它。但是,存在一些限制:在同步代码块中,缓存不会使用其他页面的更改进行更新,并且您需要异步读取一次值以填充缓存。
内容.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'
});
背景.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);
}
});
}
- 将作用域存储在JSON中
- 使用javascript存储变量的最安全方式
- 当图像转换为本地存储的DataURL时,EXIF被删除
- 如何在chrome扩展中存储数据/结果,以及如何使用setTimeout使其只被调用一次
- 如何有效地将游戏数据存储在URL查询字符串中
- Ember.js-接口状态应该存储在哪里
- 如何解雇“;铁局部存储负载”;事件
- 本地存储中的字符串到字节数组转换
- 从jQuery调用存储在Variable中的函数
- 选项卡侦听器未被来自后台脚本的消息激活
- 推荐在JavaScript中执行存储为字符串的函数,而不是使用eval
- 通过另一个php应用程序将我的项目推送到Github存储库中
- 将数据存储在javascript数组中以供进一步使用
- 在页面卸载时写入HTML5 FileSystem API存储
- WinJS(WP8.1):从后台任务更新辅助磁贴
- 加载存储在IndexedDB中的HTML页面
- Chrome扩展程序:将数据存储在后台
- Chrome扩展程序:在后台提取数据并存储在数据库中
- 如何在后台存储Node JS Buffer数据
- 如何在后台页面中存储变量