...我有一个来自维基源的Google域列表,我将其作为值添加到HTML选择标记中,如下所示:
options.html / popup.html
<select required='true' size='1'>
<option value=".com">Default: USA</option>
<option value=".co.za">South Africa</option>
<option value=".de">Germany</option>
<option value=".fr">France</option>
<option value=".com.tw">Taiwan</option>
<option value=".com.br">Brazil</option>
</select>
<div id="status"></div>
<button id="save">Select Region</button>
<script src="options.js"></script>
用户点击Chrome扩展程序图标即可看到此列表。他们选择一个并保存到chrome.storage然后页面自动在DOMContentLoaded上恢复它。
更新:我修改了一个示例来执行存储和检索的基础知识:
Option.js
// Saves options to chrome.storage
function saveRegion() {
var userRegion = document.getElementById('regions').value;
chrome.storage.sync.set({
userRegion: userRegion,
}, function() {
// Update status to let user know options were saved.
var status = document.getElementById('status');
status.textContent = 'Options saved.';
console.log()
setTimeout(function() {
status.textContent = '';
}, 750);
});
}
// Restores select box state using the preferences
// stored in chrome.storage.
function restoreRegion() {
// Use default value = '.com'
chrome.storage.sync.get({
userRegion: '.com',
}, function(items) {
document.getElementById('regions').value = items.userRegion;
});
}
document.addEventListener('DOMContentLoaded', restoreRegion);
document.getElementById('save').addEventListener('click', saveRegion);
然后,后台页面必须使用“myRegion”的存储值来构建URL,如下所示:
background.js
function readRegion() {
// Use default value = '.com'
chrome.storage.sync.get({
userRegion: '.com',
}, function(items) {
var myRegion = items.userRegion;
console.log(myRegion);
// Console prints out my saved value e.g .com.tw
});
}
document.addEventListener('DOMContentLoaded', readRegion);
chrome.contextMenus.create({
"title": "Web", //
"contexts":["selection"],
"onclick": IncognitoSearch
});
function IncognitoSearch(ocd) {
console.log(myRegion);
// Console prints out undefined
var contextSearch = 'http://www.google'+ myRegion +'/search?q=' + ocd.selectionText;
chrome.windows.create({"url": contextSearch, "incognito": true});
console.log(contextSearch);
// Console prints out http://www.googleundefined/search?q=etcetera
}
控制台打印出未定义的MyRegion的第二个日志。
如何使用我检索到的存储变量?
答案 0 :(得分:1)
API是异步的。因此,您应该使用回调(和回调链)来使用这些值。那,或Promises。回调示例:
function readRegion(callback) {
// Use default value = '.com'
chrome.storage.sync.get({
userRegion: '.com',
}, function(items) {
// The value is usable here..
callback(items.userRegion);
});
// But not here
}
function IncognitoSearch(ocd) {
readRegion(function(myRegion) {
var contextSearch = 'http://www.google'+ myRegion +'/search?q=' + ocd.selectionText;
chrome.windows.create({"url": contextSearch, "incognito": true});
});
}