Javascript 使用 window.open() 下载文件,如何不删除 URL 中的 #?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31923255/
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:23:50  来源:igfitidea点击:

Using window.open() to download file, how to not remove the # in URL?

javascript

提问by Christine268

So I am using JavaScript to download a file when an element is clicked like so:

因此,当单击元素时,我使用 JavaScript 下载文件,如下所示:

HTML

HTML

<p onclick="download()">Click Here</p>

JavaScript

JavaScript

function download(){
    window.open("file.pdf")
}

Before the element is clicked, there is some #text in the URL like so: folder/subfolder/index.html#text

在点击元素之前,URL 中有一些 #text,如下所示: folder/subfolder/index.html#text

If the file opens up in the browser it replaces the current tab and when you press the back button to return to the page (such as with PDF), any #text staysin the URL. However, if the file is simply downloaded any #text gets removed.

如果文件在浏览器中打开,它会替换当前选项卡,当您按后退按钮返回页面时(例如使用 PDF),任何 #text 都会保留在 URL 中。但是,如果只是下载文件,则任何 #text 都会被删除

How can I make it so #text is not removed or how could I return it to the URL? Since the page doesn't actually reload I am unable to put code in that might detect what #text should be in the URL. What could be another workaround?

我怎样才能让它不删除 #text 或者我怎样才能将它返回到 URL?由于页面实际上并未重新加载,因此我无法将可能检测到 URL 中的 #text 内容的代码放入其中。什么可能是另一种解决方法?

The issue I am having is that one link downloads a file that doesn't open in the browser (not a PDF) so it causes the #text to disappear. Then, when I click on another link that does open a file in the browser (a PDF) when I click the back button, the #text is gone, but it is what allows my program to know what view to be on.

我遇到的问题是一个链接下载了一个无法在浏览器中打开的文件(不是 PDF),因此它会导致 #text 消失。然后,当我单击后退按钮时,当我单击在浏览器中打开文件(PDF)的另一个链接时,#text 消失了,但它允许我的程序知道要打开的视图。

回答by machinehead115

Use window.open("file.pdf", "_blank"). This will open up a new tab temporarily to download the file then close it leaving the original page and URL in tact.

使用window.open("file.pdf", "_blank"). 这将临时打开一个新选项卡来下载文件,然后关闭它,保留原始页面和 URL。