Simple Homepage custom.js script

I have my Homepage set up with links to service.domain.tld as I am using a cloudflare tunnel. I click on Immich, it takes me to immich.mydomain.tld. I would prefer to go to ip:port when I'm on my home network though. I've tried WatchYourPorts, bookmarking ip:port and more, but I've realized I can do it with Homepages customjs script. I was lucky enough that for each service you have on your homepage, there are 2 links: one on the icon and one on the card itself. This scripts changes the icon link to the local service url and leaves the card's link intact to whatever url you have set in services.yaml. Maybe it helps someone, i made it for me tbh, also share any other scripts if you use this feature.

const ip = '192.168.X.XXX' // http://ip:port
const changeToLocal = () => {
    document.querySelectorAll('li.service').forEach(service => {
        const port = service.id?.slice(1) || null
        if (port) {
            const link = service.querySelector('a')
            if (link) {
                link.href = `http://${ip}:${port}`
            }
        }
    })
}
changeToLocal()
window.addEventListener('hashchange', changeToLocal) // if you have tabs

This takes into account if you have tabs as it would revert when you change tabs so that eventListener handles this and also if you don't have IDs set up.

Oh yeah, to make it work, you need to use IDs like in the example below in your services.yaml. And whenever you add a new service, don't forget to add the ID.

Pihole:
    id: "p8888"
    icon: icon.png
    ...

This adds an ID to each service element in HTML document so we can reference it to retrieve the port of that service. For example "p8888" means Pihole is running GUI on port 8888. We need any letter because IDs cannot contain only numbers, so i chose "p" for "port".

So, copy the scripts into your /config/custom.js, add in your IDs to all your services (i've taken into account if some services don't have ports like Diun for example, doesn't have a GUI, don't add an ID there) and it should work. If it doesn't, go into Cloudflare > your domain > Caching > Configuration > Purge everything (it should work from the get go on your homepages ip:port, but cloudflare has caching in place).

Now you click the icon it goes to your local url and you click the card, it takes you to your service.mydomain.tld