JS 下載 彈框被攔截解決方案
最新解決方案:
新打開頁面, 在設置地址, 這樣就不存在問題
var newTab = window.open('about:blank') newTab.location.href = url;

Paste_Image.png
總結[方法還是存在問題]
- 早期下載的簡單用法 :
window.open(downloadUrl)
- 下載彈框會被攔截, 解決方案是使用 form 來實現
//Jquery 版, 多次下載防止,添加多個 form if ($('#_downloadWin').length > 0) { $('#_downloadWin').attr('action', url); $('#_downloadWin input').val(path);} else { // 傳參 則在 form 里面 添加 隱藏域(<input type="hidden"/>) $('body').append($(`<form id="_downloadWin" action="${url}" target="_blank" method="get"><input name="path" type="hidden" value="${path}" /></form>`)); } $('#_downloadWin').submit();
//JavaScript版 var f = document.createElement("form"); document.body.appendChild(f); var i = document.createElement("input"); i.type = "hidden"; f.appendChild(i); i.value = "5"; i.name = "price"; f.action = "aa.asp"; //下載的url 地址 f.submit();
問題描述與解決方案
早期下載文件的時候,是直接使用 window.open(downloadUrl)
這種簡單粗暴的方法來實現的.
但是到目前(2016.05.17), window.open 已經被大部分的主流瀏覽器給攔截了, 如下圖, 需要人工在點擊一次允許打開鏈接. 這樣大大的降低了 友好的交互.

Paste_Image.png
於是需要尋找新的解決方案, 就使用 form 表單元素來進行下載, 注意 Form 表單的 target 要設置為 _blank* 在新的窗口打開,這樣就不會影響本頁面