Force download scripts have been an important part of internet usability for a long time. I can attest to that by the number of times I've implemented this feature on the server side and the popularity of my PHP Force Download post, even to this day. With the web world having moved much more the client side, I started looking for a method to force download without the need of a server, and I found it....right in the Firefox DevTools Debugger!
长期以来,强制下载脚本一直是Internet可用性的重要组成部分。 我可以通过在服务器端实现此功能的次数以及我的PHP Force Download帖子的流行程度证明这一点,直到今天。 随着网络世界在客户端方面的发展,我开始寻找一种无需服务器即可强制下载的方法,然后在Firefox DevTools Debugger中找到了它。
JavaScript (The JavaScript)
The function to do this is quite small and relies on URL.createObjectUrl
:
执行此操作的函数非常小,并且依赖于URL.createObjectUrl
:
function downloadFile(data, fileName, type="text/plain") {
// Create an invisible A element
const a = document.createElement("a");
a.style.display = "none";
document.body.appendChild(a);
// Set the HREF to a Blob representation of the data to be downloaded
a.href = window.URL.createObjectURL(
new Blob([data], { type })
);
// Use download attribute to set set desired file name
a.setAttribute("download", fileName);
// Trigger the download by simulating click
a.click();
// Cleanup
window.URL.revokeObjectURL(a.href);
document.body.removeChild(a);
}
The function injects an <a>
element into the body, sets it URL to a Blob
value to the text content of the destination file, and clicks the element to trigger the download. The element remains hidden during the process and is removed from the DOM immediately after the click()
call. As soon as the function is called, the browser's download prompt is displayed.
该函数将<a>
元素注入到正文中,将其URL设置为目标文件的文本内容的Blob
值,然后单击该元素以触发下载。 该元素在此过程中保持隐藏状态,并在click()
调用后立即从DOM中删除。 调用该函数后,将立即显示浏览器的下载提示。
I look forward to learning more about both createObjectURL
and Blob
; those two are the true magic of this technique!
我期待学习有关createObjectURL
和Blob
更多信息; 那两个才是这项技术的真正魔力!
Shout out to Sneha Jain for implementing this great technique within the Firefox DevTools debugger!
向Sneha Jain大喊,以在Firefox DevTools调试器中实现这项出色的技术!