我正在开发一个项目,其中有一个 AJAX 调用,该调用以包含 excel 文件的 blob 进行响应。我希望代码在收到响应时以下载方式打开文件。这是回调:
var blob = new Blob([response.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
var objectUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
var header = response.headers("Content-Disposition");
a.download = header.substring(header.indexOf("filename=") + "filename=".length);
a.href = objectUrl;
document.body.appendChild(a);
console.debug("Clicking a tag");
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(objectUrl);
此代码在 chrome 中工作正常,但在 firefox 中,当 a.click() 触发时没有任何反应。打印调试语句,以便我知道回调正在发生。另外,由于某种原因,如果我在 a.click()
上放置一个断点,它就可以正常工作。
有人可以解释一下为什么点击只能在 Debug模式下起作用吗?
最佳答案
Firefox 对于此类事情有一些保护措施或者只是奇怪的行为。我不知道推导过程,但在单击之前返回浏览器一会儿通常会清除它:
// ...
a.href = objectUrl;
document.body.appendChild(a);
setTimeout(function() {
a.click();
document.body.removeChild(a);
window.URL.revokeObjectURL(objectUrl);
}, 0);
// ...
请注意,setTimeout
后面的代码将先于 setTimeout
的内容运行。
您甚至可能需要两个:
// ...
a.href = objectUrl;
document.body.appendChild(a);
setTimeout(function() {
a.click();
setTimeout(function() {
document.body.removeChild(a);
window.URL.revokeObjectURL(objectUrl);
}, 0);
}, 0);
// ...
关于javascript - 如果没有断点,Firefox a.click 将不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39473635/