-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.js
69 lines (64 loc) · 2.69 KB
/
background.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === "fetchGameRatings") {
const { proxyUrl, query } = message.payload;
const gameTitle = query.split('"')[1]; // Extract game title from query
fetch(proxyUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
body: JSON.stringify({ query })
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then((gameData) => {
if (!Array.isArray(gameData) || gameData.length === 0) {
sendResponse({
success: true,
data: {
name: gameTitle,
aggregated_rating: null,
rating: null,
},
});
return;
}
const matchedGame = gameData.reduce((best, game) => {
if (!game?.name) return best;
const normalizedGameTitle = gameTitle.toLowerCase().replace(/[^a-z0-9]/g, '');
const normalizedCurrentTitle = game.name.toLowerCase().replace(/[^a-z0-9]/g, '');
const isMatch = normalizedCurrentTitle.includes(normalizedGameTitle) ||
normalizedGameTitle.includes(normalizedCurrentTitle);
if (isMatch && (game.aggregated_rating || game.rating)) {
if (!best || !best.rating) return game;
if ((game.aggregated_rating && game.rating) && (!best.aggregated_rating || !best.rating)) {
return game;
}
}
return best;
}, null);
if (!matchedGame) {
sendResponse({
success: true,
data: {
name: gameTitle,
aggregated_rating: null,
rating: null,
},
});
} else {
sendResponse({ success: true, data: matchedGame });
}
})
.catch((error) => {
console.error("Error fetching game ratings:", error);
sendResponse({ success: false, error: error.message });
});
return true;
}
});