2017-09-15 259 views
0

我想做一個擴展,需要保存一些文本(URL)。數據的設置看起來不錯,但試圖檢索數據是問題。chrome.storage.local.get沒有獲取數據

擴展清單在內容腳本區域中同時具有彈出式JavaScript和內容JavaScript。

{ 
    "manifest_version": 2, 
    "name": "Extension_Name", 
    "version": "0.0.1", 
    "browser_action": { 
     "default_title": "Extension_title", 
     "default_icon": "icon.png", 
     "default_popup": "popup.html" 
    }, 
    "permissions": ["storage"], 
    "content_scripts": [ 
     { 
      "matches": [ 
       "<all_urls>" 
      ], 
      "js": ["content.js","popup.js"] 
     } 
    ] 
} 

的網址會存儲在瀏覽器本地存儲區:

var b = document.getElementById("l"); //l is a button 
b.onmouseup = function() { 
    var r = prompt("Please enter the website to add."); 
    var g = []; 
    chrome.storage.local.get("whitelist", function (i) { 
     if (i['whitelist'] !== undefined) { 
      var g = i['whitelist']; 
     } 
    }); 
    g.push(r); 
    chrome.storage.local.set({ 
     "whitelist": g 
    }, function() { 
     console.log("done") 
    }); 
} 

這似乎是工作,我可以手動輸入的數據get函數。但是我無法找到在content.js

//getting website whitelist 
d = null; 
var inw = false; 
chrome.storage.local.get("whitelist", function (p) { 
    d = p['whitelist']; 
}); //why doesnt this work??? 
console.log(d); //testing (returns null in the console...) 
for (var j in d) { //this script doesnt run because d is not set to an array 
    alert(window.location.host.replace(/\./g, "")); 
    if (d[j].replace(/\./g, "").replace(/:\/\//g, ".") 
           .split(".")[1] === window.location.host.replace(/\./g, "")) { 
     inw = true; 
     alert("true"); 
    } 
} 
+2

相關:[如何從異步調用返回響應?](https://stackoverflow.com/q/14220321) – Makyen

回答

0

我看到一些可能出現的問題要使用的數據的方法:

在你的第二個片段中,var g = i['whitelist']在新的更窄的範圍內聲明,並且不使用原始的g。另外,g.push(r)中的g仍然是[],因爲它在chrome.storage.local.get()與現有白名單使用它的回調函數之前執行。

// edited version 
var g = []; 
chrome.storage.local.get("whitelist", function(i) { 
    if (i['whitelist'] !== undefined) { 
     g = i['whitelist']; 
    } 
    g.push(r); 
    chrome.storage.local.set({"whitelist": g}, function(){console.log("done")}); 
}); 

在第三個片段中,沒有使用在回調返回的值,你的console.log(d)因爲之前d由回調改變了它正在運行爲空。

// edited version 
chrome.storage.local.get("whitelist", function(p) { 
    d = p['whitelist']; 
    console.log(d); 
    for (var j in d) ... 
});