如何从ContentScript中的chrome.storage获取颜色

时间:2019-01-08 17:58:55

标签: javascript google-chrome-extension content-script

我将background.js中的chrome.storage中的颜色值设置为这样:

document.addEventListener('DOMContentLoaded', function() {
    var c = document.getElementById('button_confirm');
    var ic = document.getElementById('input_color');

    c.addEventListener('click', function() {

        chrome.storage.loc.set({"value": ic.value}, function() {
        console.log("The value stored was: " + ic.value);
    });

    });
});

然后我想从contentScript的存储中获取它,并将值应用为边框的颜色,如下所示:

    var links = document.querySelectorAll("link[rel]");
var as = document.querySelectorAll("a[href]"); //doplnit i kdyby nebyl odkaz na a ale například button
var hovno;


for (var i = 0, len = links && links.length; i < len; ++i)
{
  var link = links[i];
  var a = as[i];

  if (link.rel == "prerender")
  {
    chrome.runtime.sendMessage({ "newIconPath" : "48.png" });

    var prerendered_href = link.href; 

    for (var j = 0, len = as && as.length; j < len; ++j)
    {
        var a = as[j];

        if(a != "")
        {
            if(extractURL(prerendered_href) == extractURL(a.href)){
                chrome.storage.local.get(["value"], function(result) {
                    a.setAttribute("style", "border: 2px dashed "+ hovno +"; display: inline-block !important;");
                });
            }
        }
    }   

  }
  else{
    chrome.runtime.sendMessage({ "newIconPath" : "48-gray.png" });
  }
}   



function extractURL(Adress){
    var pathname = new URL(Adress).pathname;
    var domain = new URL(Adress).hostname.replace("www.","");

    return domain+pathname;
}

总是抛出错误,说“ hovno”是不确定的。我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

将最后一行移动到内部回调函数中,例如:

chrome.storage.local.get(["value"], function(result) {
      console.log('Value currently is ' + result.value);
      hovno = result.value;
      a.setAttribute("style", "border: 2px dashed "+ hovno +"; display: inline-block !important;");
    });

答案 1 :(得分:0)

它应该是.local而不是.loc,并且.get函数是异步的,它接受一个函数作为回调。这意味着a.setAttribute(....)语句是在设置hovno变量之前执行的。

要解决此问题,您可以执行以下操作:

chrome.storage.local.get(["value"], function(result) {
    a.setAttribute("style", "border: 2px dashed "+ result.value +"; display: inline-block !important;");
});