gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:43:41 25 4
gpt4 key购买 nike

我有这样的东西:

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

getDownloadLink方法必须先POST获取url,然后通过window.open(url)触发下载,但是我发现浏览器会阻止window.open行为。我怎样才能防止这种情况发生?

我在stackoverflow中看到很多类似的问题,但我仍然没有找到解决我的问题的方法。我发现 aws s3 页面做了类似的事情,该页面不会被浏览器阻止。所以...我认为必须有某种方法来处理这个问题。

最佳答案

不要使用window.open,只需让浏览器执行它已经知道的 HTML 操作:构建一个链接 anchor ,然后单击它。

// 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);
}

通过这种方式,您可以告诉浏览器“以正常方式打开链接”,它会很乐意这样做,而不是阻止历史上用于弹出窗口和其他可疑目的的可疑 API。

关于javascript - 如何打开网址并下载而不被阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52142986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com