【问题标题】:Chrome extensions: storage listener for only one stored variableChrome 扩展:仅用于一个存储变量的存储侦听器
【发布时间】:2017-09-11 14:51:02
【问题描述】:

popup.js:

...
chrome.storage.sync.set({'source': source, 'active': active, 'secs': secs, 'domain': domain}, function() {
    console.log('Settings saved');
});
...

background.js:

chrome.storage.onChanged.addListener(function(tab) {
    //something
});

那么,我可以为(例如)“活动”的变化添加一个监听器吗?

【问题讨论】:

  • 你尝试的时候发生了什么?
  • 正如您在文档中看到的,任何更改都会调用侦听器。
  • 如果我更改任何存储变量的值,它将启动该函数。谢谢 wOxxOm

标签: javascript api google-chrome-extension storage actionlistener


【解决方案1】:

我知道这个答案已经有好几年了,但是这个问题出现在我的谷歌搜索中,并且当前的答案效率低下,因为可以直接查找而不是迭代。这段代码应该会更好:

chrome.storage.onChanged.addListener(function(changes, namespace) {
    if ("active" in changes) {
        console.log("Old value: " + changes.active.oldValue);
        console.log("New value: " + changes.active.newValue);
    }
});

【讨论】:

    【解决方案2】:

    您必须在侦听器中为特定键添加 if 或 switch 语句,如下所示;

    chrome.storage.onChanged.addListener(function(changes, namespace) {
       for(key in changes) {
         if(key === 'active') {
           // Do something here
         }
       }
     });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-06
      • 1970-01-01
      相关资源
      最近更新 更多