gpt4 book ai didi

javascript - 存储 chrome 扩展选项而不关闭选项模式

转载 作者:行者123 更新时间:2023-12-03 06:20:41 25 4
gpt4 key购买 nike

我有一个 chrome 扩展,其中的选项通过 manifest.json 中的 options_ui 标记设置。我可以保存选项,但我注意到必须关闭选项模式才能使 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);

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);
}
});

最佳答案

您可以听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);
}
}
});

关于javascript - 存储 chrome 扩展选项而不关闭选项模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38887143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com