简体   繁体   English

如何打开网址并下载而不被阻止

[英]How to open an url and download without being block

I have something like this: 我有这样的事情:

<a 
  onClick={e => { getDownloadLink()
                     .then(url => window.open(url)) }}>Download</a>

the getDownloadLink method have to first POST to get a url and then trigger the download by window.open(url) ,but I found that the browser will block the window.open behavior. getDownloadLink方法必须首先通过POST来获取URL,然后通过window.open(url)触发下载,但是我发现浏览器将阻止window.open行为。 How can I prevent that? 我该如何预防?

I see a lot of questions similar in stackoverflow, but I still didn't find a method to solve my problem. 我在stackoverflow中看到了很多类似的问题,但是我仍然没有找到解决问题的方法。 And I found that the aws s3 page do something similar, the page will not being blocked by browser. 而且我发现aws s3页面做了类似的事情,该页面不会被浏览器阻止。 So... I think there must be some method to handle this. 所以...我认为必须有某种方法可以解决这个问题。

Don't use window.open , just make the browser do what it already knows to do with HTML: build a link anchor, then click it. 不要使用window.open ,只需使浏览器执行它已经知道的与HTML关联的操作:构建一个链接锚,然后单击它。

// create an temporary, invisible link and open it in a new tab
function openURL(url) {
  var a = document.createElement("a");
  a.setAttribute("target", "_blank");
  a.href = url;
  a.style.display = "none";
  // you can't click a link unless it's part of the document:
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

This way you're telling the browser to just "open a link the normal way", and it'll happily do so instead of blocking questionable APIs that have a history of being used for popups and other questionable purposes. 通过这种方式,您告诉浏览器只是“以正常方式打开链接”,并且它将高兴地这样做,而不是阻止具有可用于弹出窗口和其他可疑目的的历史的可疑API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM