You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chrome插件如何将chrome.storage.sync的值传递到content script使用

问题修复说明

你的代码存在3处核心错误,修正后即可正常在content script中获取到用户保存的输入值:

  1. 存储键名不一致+拼写错误:popup.js中存储时用的键名是maxBidDeal,但main.js里读取时先后写错为MaxBidDeal(大小写错误)、MaxBigDeal(单词拼写错误,Bid写成了Big),键名完全不匹配自然读不到值
  2. 无效递归调用导致死循环:main.js的deals函数中,你在storage.get的回调里又调用了deals(userinput),会导致函数无限递归直接卡死
  3. 异步逻辑顺序错误:chrome.storage.sync.get是异步API,你把操作DOM的逻辑写在了回调外面,会导致还没拿到存储值就先执行了DOM逻辑,userinput变量未定义

修正后的完整main.js代码

// highlight deals
async function deals() {
    chrome.storage.sync.get('maxBidDeal', function (data) {
        // 正确读取存储值,无值时默认设为0避免报错
        const userInput = data.maxBidDeal ? parseInt(data.maxBidDeal) : 0;
        // 所有DOM逻辑必须放在异步回调内部,保证能拿到userInput
        const cardCurrentBidValuesString = document.querySelectorAll('.auction > .auctionValue:nth-child(2) > .currency-coins.value');
        const cardStartBidValueString = document.querySelectorAll('.auction > .auctionStartPrice.auctionValue > .currency-coins.value');
        const cardBg = document.querySelectorAll('.rowContent.has-tap-callback');

        for (let i = 0; i < cardCurrentBidValuesString.length; i++) {
            let cardsCurrentBidPrice = cardCurrentBidValuesString[i].textContent.toString().split(',').join('');
            let cardsStartBidPrice = cardStartBidValueString[i].textContent.toString().split(',').join('');

            if (cardsCurrentBidPrice === '---') {
                cardsCurrentBidPrice = 0;
            }
            if (cardsStartBidPrice === '---') {
                cardsStartBidPrice = 0;
            }

            const parsedCardsCurrentBidPrice = parseInt(cardsCurrentBidPrice);
            const parsedCardsStartBidPrice = parseInt(cardsStartBidPrice);

            if (parsedCardsCurrentBidPrice < userInput && parsedCardsStartBidPrice < userInput) {
                cardBg[i].style['background-color'] = '#0311c3';
            }
        }
    });
}

chrome.runtime.onMessage.addListener((message) => {
    if (message.startSearch) {
        startSearch();
    } else if (message.startDeals) {
        deals();
    }
});

console.log('content loaded');

内容的提问来源于stack exchange,提问作者exec85

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 13:48:00