[英]Automatic file downloads limited to 10 files on Chrome browser
I have a webpage where we generate PDFs based upon the user selection of on-page items.我有一个网页,我们根据用户选择的页面项目生成 PDF。 This causes a postback (it's an ASP.NET WebForms page) which creates the PDFs server-side.这会导致创建 PDF 服务器端的回发(它是一个 ASP.NET WebForms 页面)。 An <a class="documentDownload">
tag is then added to the page for each item.然后将<a class="documentDownload">
标记添加到每个项目的页面。
When the page reloads in the browser the following jQuery script is executed to automatically download the files (if the user had chosen a auto-download option):当页面在浏览器中重新加载时,将执行以下 jQuery 脚本以自动下载文件(如果用户选择了自动下载选项):
var divHost = document.createElement("div");
divHost.id = "elmntDnldLinks";
divHost.style.display = "none";
document.body.appendChild(divHost);
setTimeout(function() {
$(".documentDownload").each(function(idx, val) {
var lnkDownload = $(val),
save = document.createElement("a");
save.href = lnkDownload.attr("href");
save.download = lnkDownload.attr("download");
save.target = "_blank";
divHost.appendChild(save);
save.click();
});
}, 1000);
This script has a delay of 1 second, then for each .documentDownload element it creates a new <a>
element with the same href
attribute of the original element, appends it to a newly-added hidden element, then programmatically clicks it.此脚本有 1 秒的延迟,然后对于每个 .documentDownload 元素,它会创建一个具有与原始元素相同的href
属性的新<a>
元素,将其附加到新添加的隐藏元素,然后以编程方式单击它。
[ This strategy of creating new links and clicking those instead of clicking the original DOM elements gets around a browser security measure. [这种创建新链接并单击这些链接而不是单击原始 DOM 元素的策略绕过了浏览器安全措施。 ] ]
This works perfectly well in Firefox but Chrome never downloads more than 10 files.这在 Firefox 中运行良好,但 Chrome 从不下载超过 10 个文件。 Why?为什么? I can see, for example, 15 links on the page and in the hidden element, but only 10 files are downloaded.例如,我可以在页面和隐藏元素中看到 15 个链接,但只下载了 10 个文件。
If you pause for a second between each 10 downloads, all of them will work in Chrome.如果您在每 10 次下载之间暂停一秒钟,则所有这些都将在 Chrome 中运行。
I used async timeout function for this workaround:我为此解决方法使用了异步超时功能:
function pause(msec) {
return new Promise(
(resolve, reject) => {
setTimeout(resolve, msec || 1000);
}
);
}
async function downloadAll(elements) {
var count = 0;
for (var e in elements) {
download(elements[e]); // your custom download code here, click or whatever
if (++count >= 10) {
await pause(1000);
count = 0;
}
}
}
Simple timeouts multiplied by element counter could probably work too, but I did not test it.简单的超时乘以元素计数器也可能有效,但我没有测试它。
You can do a pause in your downloads like that您可以像这样暂停下载
function sleep(milliseconds) {
let timeStart = new Date().getTime();
while (true) {
let elapsedTime = new Date().getTime() - timeStart;
if (elapsedTime > milliseconds) {
break;
}
}
}
$("#aDescarga")[0].click();
$("#aDescarga").attr("href","");
if (i > 9) {
sleep(2000);
i = 0;
} else {
i = i + 1;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.