HR-Collector/Extension/background.js
2024-12-08 20:19:07 +01:00

70 lines
No EOL
2.9 KiB
JavaScript

importScripts("./API.js");
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === "updateHorseData") {
// Kein async/await mehr in diesem Aufruf
updateHorseButton();
}
// Kein return true erforderlich, da wir kein asynchrones sendResponse nutzen
});
function sendMessageAsync(tabId, message) {
return new Promise((resolve, reject) => {
chrome.tabs.sendMessage(tabId, message, (response) => {
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
} else {
resolve(response);
}
});
});
}
function updateHorseButton() {
console.log("Updating horse data");
// Aktiven Tab ermitteln
new Promise((resolve) => {
chrome.tabs.query({ active: true, currentWindow: true }, resolve);
})
.then((tabs) => {
if (!tabs || tabs.length === 0) {
console.error("No active tab found.");
return; // Beende die Kette
}
const activeTabId = tabs[0].id;
// Schritt 1: Basisdaten des Pferdes holen
sendMessageAsync(activeTabId, { action: "getHorseBasicData" })
.then((basicDataResponse) => {
if (!basicDataResponse || !basicDataResponse.success) {
console.error("Failed to get horse basic data:", basicDataResponse ? basicDataResponse.message : "No response");
return; // Beende die Kette
}
console.log("Horse data received:", basicDataResponse.data);
const horseData = basicDataResponse.data;
// Pferd beim Backend prüfen
getHorseLoadStateAPIAsync(horseData.id)
// Basisdaten an die API senden
setBaseDataHorseAPI(horseData.id, horseData)
.then(() => {
console.log("Base data updated in API for horse ID:", horseData.id);
// Schritt 2: Aktuelle Horse-Daten holen (abhängig vom aktiven Tab)
return sendMessageAsync(activeTabId, { action: "getHorseCurrentData", data: { id: horseData.id } })
.then((currentDataResponse) => {
if (!currentDataResponse.success) {
console.error("Failed to get current horse data. Error:", currentDataResponse.message);
return;
}
console.log("Current horse data received:", currentDataResponse.data);
});
});
console.error("Error updating horse data:", error);
});
});
}