存储chrome扩展选项而不关闭选项模式

时间:2016-08-11 04:12:26

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

我有一个chrome扩展程序,其选项通过manifest.json中的options_ui标记设置。我可以保存选项但是我注意到必须关闭选项模式才能使chrome.storage.sync.set函数完成保存选项。即使选项模式未关闭,如何在单击“保存”时强制保存选项?

options.js:

function save_options() {
  var hideAds = document.getElementById('hideAds').checked;

  chrome.storage.sync.set({
        hideAds: hideAds
  }, function() {
    // Update status to let user know options were saved
        var status = document.getElementById('status');
    status.textContent = 'Options successfully saved...';
    setTimeout(function() {
      status.textContent = '';
    }, 1000);
  });
}

// Restores checkbox state using the preferences stored in chrome.storage.
function restore_options() {
  // Use default values
  chrome.storage.sync.get({
        hideAds: false
  }, function(items) {
        document.getElementById('hideAds').checked = items.hideAds;
  });
}

document.addEventListener('DOMContentLoaded', restore_options);
document.getElementById('save').addEventListener('click', save_options);

的manifest.json:

{
  "name": "Redesign",
  "version": "1.0",
  "manifest_version": 2,
  "options_ui": {
    "page": "options.html",
    "chrome_style": true
  }
}

编辑:在下面添加没有获得最新选项的background.js代码(在选项页面上单击“保存”按钮之后),除非选项模式已关闭。下面的alert行仅在选项模式关闭后输出旧保存的选项值...和新保存的值。

chrome.tabs.onUpdated.addListener(function(tabId, info, tab) {
    if (info.status == 'complete') {
            chrome.storage.sync.get(['hideAds'], function(items) {

                if(typeof items.hideAds !== 'undefined') {
                   hideAds = items.hideAds;
                   alert(hideAds);
                }
            })
            doSomething(tab);
        }
});

1 个答案:

答案 0 :(得分:0)

您可以在后台页面中收听chrome.storage.onChanged事件(您永远不需要收听chrome.tabs.onUpdated获取存储空间值),当一个或多个项目发生变化时会触发该事件:

chrome.storage.onChanged.addListener(function(changes, areaName) {
    if(areaName === 'sync') {
        const hideAdsChange = changes['hideAds'];
        if(typeof hideAdsChange !== 'undefined') {
            const newValue = hideAdsChange.newValue;
            console.log(newValue);
        }
    }
});