Created
October 31, 2023 22:35
-
-
Save crazy4groovy/5598ec30e07be3d6da9d8d895230f40e to your computer and use it in GitHub Desktop.
client side script that detects deployment changes, callback (JavaScript)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default function detectDeployment( | |
onDeployDetected: () => void, | |
timeoutSec = 60 * 60 // default 1 hour | |
) { | |
const scriptFiles = { cache: "" }; // as object for pointer reference | |
const profit$ = () => | |
handleDetectScriptFileChanges(onDeployDetected, scriptFiles); | |
setInterval(profit$, timeoutSec * 1000); | |
profit$(); | |
} | |
async function handleDetectScriptFileChanges( | |
onDeployDetected: () => void, | |
scriptFiles: { cache: string } | |
) { | |
let html = ""; | |
try { | |
const response = await fetch(window.location.origin); | |
if (!response.ok) { | |
throw new Error("Network response was not OK"); | |
} | |
html = await response.text(); | |
} catch (error) { | |
console.error("Deployment detection error:", (error as Error).message); | |
return; | |
} | |
const currentScriptFiles = parseScriptFiles(html).sort().join(";"); | |
if (!scriptFiles.cache) { | |
scriptFiles.cache = currentScriptFiles; | |
} else if (scriptFiles.cache !== currentScriptFiles) { | |
// If script file changes detected, then new deployment detected | |
onDeployDetected(); | |
} | |
} | |
function parseScriptFiles(html: string): string[] { | |
const parser = new DOMParser(); | |
const doc = parser.parseFromString(html, "text/html"); | |
return Array.from(doc.querySelectorAll("script")) | |
.map((script) => script.src) | |
.filter(Boolean); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment