【问题标题】:localStorage doesn't work in chrome.tabs.executeScript?localStorage 在 chrome.tabs.executeScript 中不起作用?
【发布时间】:2016-10-10 04:16:20
【问题描述】:

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

我的代码

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";
    }'
});

谢谢!

【问题讨论】:

  • 我猜你正在使用内容脚本;我的扩展也有同样的问题。解决方案是使用chrome.storage,讨论见here
  • 谢谢你的回答,你能给我一些示例代码吗(比如如何在bankgroud.js中设置以及如何进入content_script)?我红了link,我试过了,不行.......
  • 有一些有用的例子here。这有帮助吗?
  • no....我想在 popup.js 中设置一个值并在 content_script 中获取值,设置chrome.storage.sync.set({'Message': json.data},function(){}); 和获取chrome.storage.sync.get('Message', function(){}),我像他的例子一样写了这个,但是它不起作用...
  • 我找到了答案:enter link description here

标签: google-chrome-extension google-chrome-app


【解决方案1】:

@Noam Hacker,你是对的。需要使用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

此脚本将内容设置为 chrome 存储

//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");
});
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    • 2015-10-27
    • 2017-07-27
    • 1970-01-01
    • 2012-09-09
    相关资源
    最近更新 更多