我做了一个chrome扩展程序,该扩展程序从JSON文档中获取价格并将其插入网站,但价格顺序错误。该网站是csgoempire.com/withdraw
我尝试为chrome.runtime.sendMessage设置超时,但这只是在开始时就延迟了,而不是在每次循环运行时都如此。
content.js
function replacePrices() {
let skinNumber = 1;
console.log("Changing Prices");
let prices = document.getElementsByClassName('item__price');
var priceNumber = 0;
for (elt of prices) {
var skinNick = document.getElementsByClassName("px-2");
let skinFullName = skinNick[skinNumber].textContent;
let containsFactoryNew = skinFullName.includes('Factory New');
let containsMinimalWear = skinFullName.includes('Minimal Wear');
let containsFieldTested = skinFullName.includes('Field-Tested');
let containsWellWorn = skinFullName.includes('Well-Worn');
let containsBattleScarred = skinFullName.includes('Battle-Scarred');
let isBundle = skinFullName.includes('Bundle');
if (isBundle === true) {
let price = 'Bundle';
} else {
if (containsFactoryNew === true || containsMinimalWear === true || containsFieldTested === true || containsWellWorn === true || containsBattleScarred === true) {
skinWear = '(' + skinFullName + ')';
skinFullName = '';
} else {
skinFullName = skinFullName.trim();
skinFullName = skinFullName.replace(/\s\s+/g, ' | ');
skinFullName = skinFullName + ' ' + skinWear;
console.log(skinFullName);
chrome.runtime.sendMessage(
{contentScriptQuery: "queryPrice", itemURL: skinFullName},
price => {
prices[priceNumber].innerHTML = prices[priceNumber].innerHTML + ' | ' + price;
prices[priceNumber].style.cssText = 'color: silver; font-size: .8125rem; font-weight: 700; font-family: Lato,sans-serif;';
priceNumber = priceNumber + 1;
});
skinWear = '';
}
}
// http://steamcommunity.com/market/priceoverview/?appid=730¤cy=3&market_hash_name=StatTrak%E2%84%A2 M4A1-S | Hyper Beast (Minimal Wear)
skinNumber = skinNumber + 1;
}
btnReplace.innerHTML = "Reload Steam Market Prices";
}
background.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.contentScriptQuery == "queryPrice") {
var url = "https://pixelboii.wtf/steamvalue.json";
var skinFullName = request.itemURL;
fetch(url)
.then(res => res.json())
.then(price => {
sendResponse(price.items_list[skinFullName].price["7_days"].average);
})
.catch(err => { throw err });
return true; // Will respond asynchronously.
}
});
应该加载价格,以便使其与放置在下面的商品匹配,但是目前,它们彼此混淆。没有错误代码。
答案 0 :(得分:0)
您遇到的问题是并行访问变量的经典问题。本质上,发生的是每次获取价格时priceNumber都会增加1,但是有可能同时返回2个价格获取,同时更新DOM,然后同时增加,但是它们是重新使用相同的priceNumber值来确定在何处插入其价格。
解决此问题的最简单方法是,还返回价格旁边的skinFullName,然后在skinFullName和索引之间建立一个Map。这样,您可以基于skinFullName查找固定索引,而不必依赖以与获取价格相同的顺序到达的皮肤价格获取(在这种情况下也不保证)。