【问题标题】:Storing chrome extension options without closing options modal存储 chrome 扩展选项而不关闭选项模式
【发布时间】:2016-08-11 04:12:25
【问题描述】:

我有一个 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);
        }
});

【问题讨论】:

  • 为什么您认为在关闭模式之前不会保存选项?
  • 添加了 background.js 代码,上面输出旧的选项值,直到选项模式窗口关闭。

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


【解决方案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);
        }
    }
});

【讨论】:

    猜你喜欢
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    • 1970-01-01
    相关资源
    最近更新 更多