我有一个 chrome 扩展,其选项通过options_ui
manifest.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);
}
});