5+APP 实现更新下载
<script type='text/javascript'>
document.addEventListener('plusready', function() {
function getCurrentVersion() {
return plus.runtime.versionCode
}
async function getServerVersion() {
const xhr = new XMLHttpRequest()
xhr.open('POST', '服务器地址')
return new Promise((resolve, reject) => {
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
const jsonData = JSON.parse(xhr.responseText)
resolve(jsonData.versionCode)
}
}
xhr.onerror = function() {
reject(new Error('Request failed'))
}
xhr.send()
})
}
function compareVersion(localVersion, serverVersion) {
if (serverVersion == localVersion) {
alert('当前已经是最新版本了!')
} else {
const confirmText = confirm('发现最新版本,是否立即更新?')
if (confirmText) {
downloadNewVersion()
} else {
alert('您选择了取消!')
}
}
}
function downloadNewVersion() {
alert('下载中,请勿关闭页面')
const url = '下载地址'
const dtask = plus.downloader.createDownload(url, {
method: "GET"
}, function(d, status) {
if (status == 200) {
const filePath = d.filename
plus.runtime.install(filePath, {
force: true
}, function() {
alert('安装成功,重启中...')
}, function(e) {
console.error('安装失败: ' + e.message);
alert('安装失败')
})
} else {
console.log('下载失败: ' + status)
alert('下载失败,请重新下载!')
}
})
dtask.start()
}
async function checkAndUpdateVersion() {
try {
const localVersion = getCurrentVersion()
const serverVersion = await getServerVersion()
compareVersion(localVersion, serverVersion)
} catch (error) {
console.error(error)
}
}
checkAndUpdateVersion()
})
</script>