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>

- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76