2016-06-09 114 views
0

我想用localStorage来保存和使用数据。我可以保存和使用数据,但是当我在chrome.tabs.executeScript中使用localStorage时,localStorage始终为空......为什么?localStorage在chrome.tabs.executeScript中不起作用?

我的代码

chrome.tabs.executeScript({ code: 
    'document.getElementById(":2k.en").onclick = function(){ 
     alert(localStorage.getItem("Message")); 
     document.getElementById(":2i").value = localStorage.getItem("Token"); 
     document.getElementById(":2k.jl").textContent = "it is OK"; 
    }' 
}); 

谢谢!

+0

我猜你正在使用内容脚本;我的扩展程序有同样的问题。解决方法是使用'chrome.storage',参见[here](http://stackoverflow.com/questions/3598669/cookie-or-localstorage-with-chrome-extensions/15466494#15466494)进行讨论 –

+0

谢谢你的支持答案,你可以给我一些示例代码(如如何在bankgroud.js中设置以及如何获取content_script)?我红色[链接](https://developer.chrome.com/extensions/storage.html),我试过了,它不工作....... – user2262304

+0

有一些有用的例子[这里]( https://developer.chrome.com/extensions/storage)。这有帮助吗? –

回答

0

@Noam黑客,你是对的。需要使用Chrome.storage API来存储,检索和跟踪用户数据的更改。通过使用该API,您需要声明extension manifest中的storage权限才能使用存储API。

{ 
"name": "My extension", 
... 
"permissions": [ 
"storage" 
], 
... 

}

使用get StorageArea.get(string or array of string or object keys, function callback)其回调摆脱存储一个或多个项目。一个空的列表或对象将返回一个空的结果对象。传入null以获取存储的全部内容。

background.js

该脚本将内容存储铬

//Set some content from background page 
chrome.storage.local.set({"identifier":"Some awesome Content"},function(){ 
console.log("Storage Succesful"); 
}); 
//get all contents of chrome storage 
chrome.storage.local.get(null,function (obj){ 
console.log(JSON.stringify(obj)); 
}); 

popup.js

此脚本将检索并设置内容从\ Chrome浏览器的存储

document.addEventListener("DOMContentLoaded",function(){ 
//Fetch all contents 
chrome.storage.local.get(null,function (obj){ 
console.log(JSON.stringify(obj)); 
}); 
//Set some content from browser action 
chrome.storage.local.set({"anotherIdentifier":"Another awesome Content"},function(){ 
console.log("Storage Succesful"); 
}); 
});