SwapStation_WebApp/frontend/js/page-header.js

48 lines
1.8 KiB
JavaScript

// frontend/js/page-header.js
// This function fetches the common header and injects it into the page
async function loadHeader() {
try {
const response = await fetch('_header.html');
if (!response.ok) {
throw new Error('Could not load the header file.');
}
const headerHTML = await response.text();
// Adds the header right after the opening <body> tag
document.body.insertAdjacentHTML('afterbegin', headerHTML);
} catch (error) {
console.error('Failed to load header:', error);
// Optionally, display an error to the user
}
}
// This function populates the header with data from localStorage
function populateHeaderData() {
const selectedStation = JSON.parse(localStorage.getItem('selected_station'));
if (!selectedStation) {
alert('No station selected. Redirecting...');
window.location.href = 'station_selection.html';
return;
}
const stationNameEl = document.getElementById('station-name');
const stationLocationEl = document.getElementById('station-location');
const stationIdEl = document.getElementById('station-id-display');
const productIdEl = document.getElementById('product-id-display');
if (stationNameEl) stationNameEl.textContent = selectedStation.name;
if (stationLocationEl) stationLocationEl.textContent = selectedStation.location;
if (stationIdEl) stationIdEl.textContent = selectedStation.id;
if (productIdEl) productIdEl.textContent = selectedStation.product_id;
}
// Main execution block
// We use an async function to make sure the header is loaded BEFORE we try to fill it
async function initializePageHeader() {
await loadHeader();
populateHeaderData();
}
// Run the initialization when the page content is loaded
document.addEventListener('DOMContentLoaded', initializePageHeader);