0

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

选项.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);

清单.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);
        }
});
4

1 回答 1

1

您可以在后台页面中收听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);
        }
    }
});
于 2016-08-12T00:04:40.133 回答