11.01.2024 edit based on suggestion and answer by Jason: Keep start url search parameters, account for location hash, set navigation scope and avoid breaking absolute icon paths.
manifest = document.head.querySelector('link[rel="manifest"]');
json = await fetch(href = manifest.href).then(res => res.json());
base
url = href.substringnew URL(0,window.location);
url.search href= new URLSearchParams([.lastIndexOf..new URL('/')json.start_url, +url).searchParams, 1...url.searchParams]);
json.start_url = windowurl.locationhref;
json.hrefscope = url.origin + url.pathname.substring(0, url.pathname.lastIndexOf('?usp=installed_webapp';/') + 1);
json.icons.forEach((icon) => icon.src = base +new URL(icon.src, manifest.href).href);
manifest.href = 'data:application/manifest+json,' + encodeURIComponent(JSON.stringify(json));
json;
// Find the head node linking to the original manifest.
manifest = document.head.querySelector('link[rel="manifest"]');
// Fetch the manifest and convert it to json.
json = await fetch(href = manifest.href).then(res => res.json());
// StoreCreate thea basenew url for resourcesthe referencedcurrent inlocation, keeping the manifestparameters from the original start url.
baseurl = href.substringnew URL(0,window.location);
url.search href= new URLSearchParams([.lastIndexOf..new URL('/')json.start_url, +url).searchParams, 1...url.searchParams]);
// Set the start url toand thescope. currentWill location,revert appendto parametera asnormal inbrowser thewhen originalnavigated manifestoutside of scope.
json.start_url = windowurl.locationhref;
json.hrefscope = url.origin + url.pathname.substring(0, url.pathname.lastIndexOf('?usp=installed_webapp';/') + 1);
// Convert relative icon paths relative toin the manifest into absolute paths.
// When the manifest is defined inline, the paths must be absolute and include protocol.
json.icons.forEach((icon) => icon.src = base +new URL(icon.src, manifest.href).href);
// Store the updated manifest in-placeinline in the original link node.
// Must be URI-encoded, otherwise the # in the colors would cause parsing errors.
manifest.href = 'data:application/manifest+json,' + encodeURIComponent(JSON.stringify(json));
// Dump the updated manifest into the console for review.
json;