my_app_remote_server_ui_app/server/frontend/getAppMetadata.js
2026-01-04 18:37:03 +01:00

83 lines
2.6 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<script>0
async function getAppMetadata(baseUrl) {
try {
const res = await fetch(baseUrl, { mode: "cors" });
const html = await res.text();
const parser = new DOMParser();
const doc = parser.parseFromString(html, "text/html");
// -------------------------------
// 1. Raccogli tutti i nomi possibili
// -------------------------------
const nameCandidates = [
doc.querySelector('meta[property="og:site_name"]')?.content,
doc.querySelector('meta[name="application-name"]')?.content,
doc.querySelector('meta[property="og:title"]')?.content,
doc.querySelector("title")?.textContent?.trim()
].filter(Boolean);
const name = nameCandidates.length > 0
? nameCandidates.sort((a, b) => a.length - b.length)[0]
: "no_name";
// -------------------------------
// 2. Raccogli icone dallHTML
// -------------------------------
const htmlIcons = [...doc.querySelectorAll("link[rel*='icon']")].map(link => ({
href: link.getAttribute("href"),
sizes: link.getAttribute("sizes") || ""
}));
// -------------------------------
// 3. Cerca il manifest.json
// -------------------------------
let manifestIcons = [];
const manifestLink = doc.querySelector('link[rel="manifest"]');
if (manifestLink) {
try {
const manifestUrl = new URL(manifestLink.href, baseUrl).href;
const manifestRes = await fetch(manifestUrl, { mode: "cors" });
const manifestJson = await manifestRes.json();
if (manifestJson.icons && Array.isArray(manifestJson.icons)) {
manifestIcons = manifestJson.icons.map(icon => ({
href: icon.src,
sizes: icon.sizes || ""
}));
}
} catch (e) {
// Manifest non accessibile o non valido
}
}
// -------------------------------
// 4. Unisci icone HTML + manifest
// -------------------------------
const allIcons = [...htmlIcons, ...manifestIcons];
// -------------------------------
// 5. Ordina per dimensione (più grande prima)
// -------------------------------
allIcons.sort((a, b) => {
const sizeA = parseInt(a.sizes.split("x")[0]) || 0;
const sizeB = parseInt(b.sizes.split("x")[0]) || 0;
return sizeB - sizeA;
});
// -------------------------------
// 6. Risolvi URL assoluto
// -------------------------------
let icon = null;
if (allIcons.length > 0) {
icon = new URL(allIcons[0].href, baseUrl).href;
}
return { name, icon };
} catch (err) {
return { name: "no_name", icon: null };
}
}
</script>