How can dark mode be saved on all pages of the site?

I’ve made a dark mode button, and my code saves the user’s preference (if they’ve chosen dark mode, when they refresh the page it will remain in dark mode). But when he goes to another page the chosen mode doesn’t apply, the other pages go back to standard mode.

How do I make it so that, regardless of the page, if the user chooses dark mode, all pages are saved in that mode?

let trilho = document.getElementById('trilho');
let body = document.querySelector('body');

// Check local storage for the user's theme preference
const theme = window.localStorage.getItem("theme");

// Set the initial theme based on localStorage
if (theme === "dark") {
    body.classList.add("dark");
    trilho.classList.add("dark"); // Ensure the button reflects dark mode
} else {
    trilho.classList.remove("dark"); // Ensure the button reflects light mode
}

// Add event listener to toggle dark mode
trilho.addEventListener('click', () => {
    trilho.classList.toggle('dark');
    body.classList.toggle('dark');

    // Update localStorage with the current theme
    if (body.classList.contains("dark")) {
        window.localStorage.setItem("theme", "dark");
        trilho.classList.add("dark"); // Dark mode button
    } else {
        window.localStorage.setItem("theme", "light");
        trilho.classList.remove("dark"); // Light mode button
    }
});