如何实现HTML按钮点击后在新标签页打开链接并触发文件下载
问题原因
- 浏览器默认弹窗拦截规则会限制
window.open调用,即使是点击事件触发的window.open也存在被误拦截的概率,导致新标签页无法正常加载下载资源。 download属性仅对同域资源生效,跨域资源通过window.open打开时,浏览器会根据资源响应头判断行为,无法保证强制触发下载,部分场景下会直接在标签页内预览资源。
解决方案
方案1:a标签嵌套button(优先选择)
直接将button包裹在原有正常工作的a标签内,不需要修改JS逻辑,完全复用原生a标签的下载能力,兼容性最好:
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> .btn { background-color: DodgerBlue; border: none; color: white; padding: 12px 30px; cursor: pointer; font-size: 20px; } .btn:hover { background-color: RoyalBlue; } /* 可选:去掉a标签默认的下划线样式 */ a { text-decoration: none; } </style> </head> <body> <a href="https://img1.wsimg.com/blobby/go/eb48d7ab-a64a-4b99-b59d-72a34da60076/downloads/Calculator.zip?ver=1621722035246" download rel="noopener noreferrer" target="_blank"> <button class="btn">Download</button> </a> </body> </html>
方案2:JS动态创建a标签触发点击
如果必须通过JS逻辑触发下载,不要使用window.open,改为动态创建a标签模拟点击:
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> .btn { background-color: DodgerBlue; border: none; color: white; padding: 12px 30px; cursor: pointer; font-size: 20px; } .btn:hover { background-color: RoyalBlue; } </style> </head> <body> <button class="btn" onclick="handleDownload()">Download</button> <script> function handleDownload() { const downloadUrl = 'https://img1.wsimg.com/blobby/go/eb48d7ab-a64a-4b99-b59d-72a34da60076/downloads/Calculator.zip?ver=1621722035246' const link = document.createElement('a') link.href = downloadUrl link.target = '_blank' link.rel = 'noopener noreferrer' link.download = '' // 临时插入到DOM中触发点击 document.body.appendChild(link) link.click() // 点击后移除临时节点 document.body.removeChild(link) } </script> </body> </html>
内容的提问来源于stack exchange,提问作者Alexis Omar
相关产品推荐
相关产品推荐

