在同一选项卡中启动下载,而无需在 Javascript 中打开新选项卡或窗口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12365534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:49:49  来源:igfitidea点击:

Launch download in the same tab without opening new tab or window in Javascript

javascriptdownload

提问by Vervatovskis

I am using this javascript function to launch download

我正在使用这个 javascript 函数来启动下载

function startDownload(url) {
   window.open(url, 'Download');
}

It works, but i want to block any new tab or new window launch, thanks.

它有效,但我想阻止任何新标签或新窗口启动,谢谢。

回答by Salketer

function startDownload(url) {

    window.location.href = url;
}

This will start the download in the same page, exactly like when you click a link without any target other than _self.

这将在同一页面中开始下载,就像您单击一个没有任何目标的链接时一样_self

To force the download of a file, make sure you send the right headers with it:

要强制下载文件,请确保随文件一起发送正确的标头:

Content-Disposition: attachment; filename="mypdf.pdf";

This will make sure that the file is not displayed in the browser instead of being downloaded. Replace the filename part with the filename you want as default on the save asdialog.

这将确保文件不会显示在浏览器中,而不是被下载。将文件名部分替换为save as对话框中您想要的默认文件名。

回答by Manse

window.openwill open a new window \ tab (depending on user preferences) ... to just download the file use

window.open将打开一个新窗口\标签(取决于用户偏好)......只下载文件使用

window.location.href = url;

You can use this if the urlreturns a downloadable file rather than a web page

如果url返回可下载的文件而不是网页,您可以使用它

回答by Krad

HTML5 solution with 'download' attribute

具有“下载”属性的 HTML5 解决方案

<a href="/images/myw3schoolsimage.jpg" download>

https://www.w3schools.com/tags/att_a_download.asp

https://www.w3schools.com/tags/att_a_download.asp

回答by GouriSankar Sahu

<a target="_parent" href="link"></a>
  • _blank - URL is loaded into a new window. This is default
  • _parent - URL is loaded into the parent frame
  • _self - URL replaces the current page
  • _top - URL replaces any framesets that may be loaded name - The name of the window
  • _blank - URL 加载到新窗口中。这是默认的
  • _parent - URL 加载到父框架中
  • _self - URL 替换当前页面
  • _top - URL 替换可能加载的任何框架集 name - 窗口的名称