chrome 存储同步输入值
chrome storage sync input value
我尝试在我的 main.js(内容脚本)中获取输入值,但我很难以某种方式完成它。我设法使用 windows.onload 方法保存了值,您可以在下面的 popup.js 中看到。但我不能把它交给内容脚本。
我想在我的内容脚本中将该值用作变量“userInput”。
popup.js:
function registerButtonAction(tabId, button, action) {
// clicking button will send a message to
// content script in the same tab as the popup
button.addEventListener('click', () => chrome.tabs.sendMessage(tabId, { [action]: true }));
}
function setupButtons(tabId) {
// add click actions to each 3 buttons
registerButtonAction(tabId, document.getElementById('start-btn'), 'startSearch');
registerButtonAction(tabId, document.getElementById('deals-btn'), 'startDeals');
registerButtonAction(tabId, document.getElementById('stop-btn'), 'stopSearch');
}
function injectStartSearchScript() {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
// Injects JavaScript code into a page
// chrome.tabs.executeScript(tabs[0].id, { file: 'main.js' });
// add click handlers for buttons
setupButtons(tabs[0].id);
});
}
injectStartSearchScript();
window.onload = function () {
document.getElementById('save-btn').onclick = function () {
let valueInput = document.getElementById('deal-ipt').value;
chrome.storage.sync.set({ 'maxBidDeal': valueInput }, function () {
alert('Saved!');
});
};
};
manifest.json:
{
"manifest_version": 2,
"name": "test app",
"description": "test desc",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": ["tabs", "<all_urls>", "storage"],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["main.js"]
}
],
"content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'"
}
main.js:
// highlight deals
async function deals() {
// let userInputBidPrice = prompt('Set max Bid Price to show deals:');
chrome.storage.sync.get('MaxBidDeal', function (data) {
let userinput = data.MaxBigDeal;
deals(userinput);
});
let cardCurrentBidValuesString = document.querySelectorAll('.auction > .auctionValue:nth-child(2) > .currency-coins.value');
let cardStartBidValueString = document.querySelectorAll('.auction > .auctionStartPrice.auctionValue > .currency-coins.value');
let cardBg = document.querySelectorAll('.rowContent.has-tap-callback');
for (let i = 0; i < cardCurrentBidValuesString.length; i++) {
cardsCurrentBidPrice = cardCurrentBidValuesString[i].textContent.toString().split(',').join('');
cardsStartBidPrice = cardStartBidValueString[i].textContent.toString().split(',').join('');
if (cardsCurrentBidPrice === '---') {
cardsCurrentBidPrice = 0;
}
if (cardsStartBidPrice === '---') {
cardsStartBidPrice = 0;
}
parsedCardsCurrentBidPrice = parseInt(cardsCurrentBidPrice);
parsedCardsStartBidPrice = parseInt(cardsStartBidPrice);
if (parsedCardsCurrentBidPrice < parseInt(userinput) && parsedCardsStartBidPrice < parseInt(userinput)) {
cardBg[i].style['background-color'] = '#0311c3';
}
}
}
chrome.runtime.onMessage.addListener((message) => {
// choose action based on received message:
if (message.startSearch) {
startSearch();
} else if (message.startDeals) {
deals();
}
});
// sanity check: content has loaded in the tab
console.log('content loaded');
所以我确定我必须以某种方式使用 chrome.storage.get 但我无法准确地弄清楚。
您的代码永远递归调用 deals
而没有实际传递值,因为您没有声明参数,然后您试图在变量范围之外使用 userinput
。
您可以像这样承诺 chrome.storage
并使用 await
:
async function deals() {
// Note that chrome.storage is already promisified in ManifestV3 since Chrome 95
let { MaxBidDeal } = await new Promise(resolve =>
chrome.storage.sync.get('MaxBidDeal', resolve));
// use MaxBidDeal right here
console.log('MaxBidDeal', MaxBidDeal);
}
我尝试在我的 main.js(内容脚本)中获取输入值,但我很难以某种方式完成它。我设法使用 windows.onload 方法保存了值,您可以在下面的 popup.js 中看到。但我不能把它交给内容脚本。 我想在我的内容脚本中将该值用作变量“userInput”。
popup.js:
function registerButtonAction(tabId, button, action) {
// clicking button will send a message to
// content script in the same tab as the popup
button.addEventListener('click', () => chrome.tabs.sendMessage(tabId, { [action]: true }));
}
function setupButtons(tabId) {
// add click actions to each 3 buttons
registerButtonAction(tabId, document.getElementById('start-btn'), 'startSearch');
registerButtonAction(tabId, document.getElementById('deals-btn'), 'startDeals');
registerButtonAction(tabId, document.getElementById('stop-btn'), 'stopSearch');
}
function injectStartSearchScript() {
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
// Injects JavaScript code into a page
// chrome.tabs.executeScript(tabs[0].id, { file: 'main.js' });
// add click handlers for buttons
setupButtons(tabs[0].id);
});
}
injectStartSearchScript();
window.onload = function () {
document.getElementById('save-btn').onclick = function () {
let valueInput = document.getElementById('deal-ipt').value;
chrome.storage.sync.set({ 'maxBidDeal': valueInput }, function () {
alert('Saved!');
});
};
};
manifest.json:
{
"manifest_version": 2,
"name": "test app",
"description": "test desc",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": ["tabs", "<all_urls>", "storage"],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["main.js"]
}
],
"content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'"
}
main.js:
// highlight deals
async function deals() {
// let userInputBidPrice = prompt('Set max Bid Price to show deals:');
chrome.storage.sync.get('MaxBidDeal', function (data) {
let userinput = data.MaxBigDeal;
deals(userinput);
});
let cardCurrentBidValuesString = document.querySelectorAll('.auction > .auctionValue:nth-child(2) > .currency-coins.value');
let cardStartBidValueString = document.querySelectorAll('.auction > .auctionStartPrice.auctionValue > .currency-coins.value');
let cardBg = document.querySelectorAll('.rowContent.has-tap-callback');
for (let i = 0; i < cardCurrentBidValuesString.length; i++) {
cardsCurrentBidPrice = cardCurrentBidValuesString[i].textContent.toString().split(',').join('');
cardsStartBidPrice = cardStartBidValueString[i].textContent.toString().split(',').join('');
if (cardsCurrentBidPrice === '---') {
cardsCurrentBidPrice = 0;
}
if (cardsStartBidPrice === '---') {
cardsStartBidPrice = 0;
}
parsedCardsCurrentBidPrice = parseInt(cardsCurrentBidPrice);
parsedCardsStartBidPrice = parseInt(cardsStartBidPrice);
if (parsedCardsCurrentBidPrice < parseInt(userinput) && parsedCardsStartBidPrice < parseInt(userinput)) {
cardBg[i].style['background-color'] = '#0311c3';
}
}
}
chrome.runtime.onMessage.addListener((message) => {
// choose action based on received message:
if (message.startSearch) {
startSearch();
} else if (message.startDeals) {
deals();
}
});
// sanity check: content has loaded in the tab
console.log('content loaded');
所以我确定我必须以某种方式使用 chrome.storage.get 但我无法准确地弄清楚。
您的代码永远递归调用 deals
而没有实际传递值,因为您没有声明参数,然后您试图在变量范围之外使用 userinput
。
您可以像这样承诺 chrome.storage
并使用 await
:
async function deals() {
// Note that chrome.storage is already promisified in ManifestV3 since Chrome 95
let { MaxBidDeal } = await new Promise(resolve =>
chrome.storage.sync.get('MaxBidDeal', resolve));
// use MaxBidDeal right here
console.log('MaxBidDeal', MaxBidDeal);
}