创建a标签然后模拟点击和直接window.open有什么区别?

看到一段代码:

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)
})
阅读 3.4k
1 个回答

window.open如果放在异步任务里,可能会被浏览器拦截页面跳出的操作。因此,会采用创建a标签,触发点击操作。

推荐问题