2

通知我的 content_script.js 设置更改的正确方法是什么?

当我将设置写入 localStorage 时,我想对内容脚本执行 sendMessage/sendRequest,以便它可以相应地应用它们。

我必须做 options.js > background.js > content_script.js

想法?

选项.js

$('#add-filter-button')
    .button()
    .click(function(event) {
        event.preventDefault();
        var userFilters = new Array();
        var newFilter = $('#add-filter').val();
        if (newFilter !== undefined && newFilter.length > 0) {
            $('#filters-box').append(new Option(newFilter, newFilter));
            $('#add-filter').val('');
            $('#filters-box option').each(function() {
                userFilters.push( $(this).text() );
            });
            localStorage['userFilters'] = JSON.stringify(userFilters);
            chrome.storage.sync.set({'userFilters': userFilters});
        }
    });

内容.js

chrome.storage.onChanged.addListener(function(changes, namespace) {
    for (key in changes) {
        var storageChange = changes[key];
        console.log('Storage key "%s" in namespace "%s" changed. ' +
            'Old value was "%s", new value is "%s".',
            key,
            namespace,
            storageChange.oldValue,
            storageChange.newValue);
        }
});
4

1 回答 1

3

使用chrome.storage.local https://developer.chrome.com/extensions/storage.html

它有事件onChanged

例如:

设置.js

chrome.storage.sync.set({'value': theValue});

内容.js

chrome.storage.onChanged.addListener(function(changes, namespace) {
  for (key in changes) {
    var storageChange = changes[key];
    console.log('Storage key "%s" in namespace "%s" changed. ' +
                'Old value was "%s", new value is "%s".',
                key,
                namespace,
                storageChange.oldValue,
                storageChange.newValue);
  }
});
于 2013-02-08T05:30:48.673 回答