在同一选项卡中启动下载,而无需在 Javascript 中打开新选项卡或窗口 [英] Launch download in the same tab without opening new tab or window in Javascript

查看:24
本文介绍了在同一选项卡中启动下载,而无需在 Javascript 中打开新选项卡或窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using this javascript function to launch download

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

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

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

推荐答案

function startDownload(url) {

    window.location.href = url;
}

这将在同一页面中开始下载,就像您点击一个除了 _self 之外没有任何目标的链接一样.

This will start the download in the same page, exactly like when you click a link without any target other than _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 as dialog.

这篇关于在同一选项卡中启动下载,而无需在 Javascript 中打开新选项卡或窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆