通知我的content_script.js更改设置的正确方法是什么?
当我将我的设置写入localStorage时,我想对内容脚本执行sendMessage / sendRequest,以便它可以相应地应用它们。
我必须要做options.js> background.js> content_script.js
思想?
options.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});
}
});
content.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);
}
});
答案 0 :(得分:2)
使用chrome.storage.local
https://developer.chrome.com/extensions/storage.html
它有事件onChanged
例如:
settings.js
chrome.storage.sync.set({'value': theValue});
content.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);
}
});