Last active
December 17, 2020 15:44
-
-
Save MattiaCostamagna/431eac43cc80a98710782a0b35a301f4 to your computer and use it in GitHub Desktop.
Keep a Single-Page-Application updated
This file contains 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
import React from 'react'; | |
const IndexHTMLURL = 'https://my.url.com/index.html' | |
class App extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
// ... | |
}; | |
} | |
async componentDidMount() { | |
// ... | |
let reloadOnNextChange = false; | |
let checkIndexInterval = setInterval(async () => { | |
reloadOnNextChange = await CheckForIndexHTMLChange(IndexHTMLURL); | |
if (reloadOnNextChange) { | |
clearInterval(checkIndexInterval); | |
} | |
}, 600000); | |
this.props.history.listen(() => (reloadOnNextChange ? window.location.reload(true) : null)); | |
// ... | |
} | |
render() { | |
return <div>{/*...*/}</div>; | |
} | |
} |
This file contains 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 const CheckForIndexHTMLChange = async (indexHTMLURL) => { | |
try { | |
let resp = await fetch(indexHTMLURL, { method: 'get', mode: 'cors' }); | |
let text = await resp.text(); | |
let r = /^.*<script.*\/(main.*\.js).*$/gim.exec(text); | |
if (!r || r.length < 2) { | |
return; | |
} | |
let remoteMainScript = r.length > 1 ? r[1] : null; | |
if (remoteMainScript === null) { | |
return; | |
} | |
let localMainScript = null; | |
let scripts = document.body.getElementsByTagName('script'); | |
for (let script of scripts) { | |
let rl = /^.*\/(main.*\.js).*$/gim.exec(script.src); | |
if (!rl || rl.length < 2) { | |
continue; | |
} | |
localMainScript = rl[1]; | |
break; | |
} | |
if (localMainScript === null) { | |
return; | |
} | |
return remoteMainScript !== localMainScript; | |
} catch (err) { | |
console.log(err); | |
return false; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment