const intervalTime = 60000
let timer = null
let oldFiles = []
let scriptUrls = []
let linkUrls = []
let scriptTags = [...document.getElementsByTagName('script')].map(tag => tag.src)
let linkTags = [...document.getElementsByTagName('link')].map(tag => tag.href)
for (const tag of scriptTags) {
if (tag && tag.includes('.js')) {
scriptUrls.push(tag.split('/').pop().replace('.js', ''))
}
}
for (const tag of linkTags) {
if (tag && tag.includes('.js')) {
linkUrls.push(tag.split('/').pop().replace('.js', ''))
}
}
oldFiles = [...new Set([...scriptUrls, ...linkUrls])]
console.log('oldFiles', oldFiles)
timer = setInterval(checkForUpdates, intervalTime)
async function checkForUpdates () {
getFilesName().then(res=>{
const scriptsList = res
console.log('oldFiles', oldFiles)
console.log('res', res)
for (const script of scriptsList) {
if (!oldFiles.includes(script)) {
updatePage(script)
return
}
}
})
}
function getScriptUrls (htmlContent) {
const scriptUrls1 = []
const scriptTags1 = htmlContent.match(/<script\b[^>]*>/gi) || []
for (const tag of scriptTags1) {
const match = tag.match(/\/([^\\/]*)\.js/)
if (match && match[1]) {
scriptUrls1.push(match[1])
}
}
return scriptUrls1
}
function getLinkUrls (htmlContent) {
const linkUrls1 = []
const linkTags1 = htmlContent.match(/<link\b[^>]*>/gi) || []
for (const tag of linkTags1) {
const match = tag.match(/\/([^\\/]*)\.js/)
if (match && match[1]) {
linkUrls1.push(match[1])
}
}
return linkUrls1
}
function updatePage (name) {
console.info(name)
console.info('该更新了')
clearInterval(timer)
alert('新版本已经发布,请点击确定或刷新页面获取最新版本!!!')
window.location.reload()
}
async function getFilesName () {
const response = await fetch(location.href)
const htmlContent = await response.text()
const scriptsList = new Set(getScriptUrls(htmlContent))
const linksList = new Set(getLinkUrls(htmlContent))
return [...new Set([...scriptsList, ...linksList])]
}