看到一段代码:
fetch('example.zip')
.then(res => res.blob())
.then(blob => {
const url = URL.createObjectURL(blob)
// 不理解的开始
let a = document.createElement('a')
a.download = 'example.zip'
a.href = url
document.body.appendChild(a)
a.click()
a.remove()
// 上面这6行和直接 ` window.open(url)` 有什么区别呢?
})
.catch(err => {
console.error(err)
})
不理解的是它和下面这段代码有什么实际意义的区别?
fetch('example.zip')
.then(res => res.blob())
.then(blob => {
const url = URL.createObjectURL(blob)
window.open(url)
})
.catch(err => {
console.error(err)
})
window.open如果放在异步任务里,可能会被浏览器拦截页面跳出的操作。因此,会采用创建a标签,触发点击操作。