admin管理员组

文章数量:1321074

I would like to trigger download with window.open() function in javascript in local. The path should start with "/". I provide URL with / to start, however, it seems like window.open() function ignore the first /. Is there a way to make it read the / , so that i can trigger download?

I would like to trigger download with window.open() function in javascript in local. The path should start with "/". I provide URL with / to start, however, it seems like window.open() function ignore the first /. Is there a way to make it read the / , so that i can trigger download?

Share Improve this question asked Jan 11, 2018 at 16:49 Brian RuchiadiBrian Ruchiadi 3611 gold badge13 silver badges29 bronze badges 2
  • "it seems like window.open() function ignore the first /" — It doesn't. You need to provide a minimal reproducible example. What is the URL you are trying to point the browser to? What is the URL of the page from which you are running the JS? What is the JS? – Quentin Commented Jan 11, 2018 at 16:51
  • the URL is pointing to my local, which is something like /Applications/XAMPP. THe URL of the page with JS is localhost:3000, but i want to ignore that. @Quentin – Brian Ruchiadi Commented Jan 11, 2018 at 16:53
Add a ment  | 

3 Answers 3

Reset to default 1

A URL starting with a / is a relative URL with an absolute path. It ignores the existing path on the URL, and calculates the new one starting from the end of the port (or hostname if there is no port, localhost in this case).

If you want to make a request to a different URL scheme (in this case file: instead of http:) then you need to use an absolute URL (i.e. state the new URL scheme explicitly).

NB: Many browsers will block requests to file: scheme URLs triggered by pages which were not served using the file: scheme for security reasons.

For security reasons browsers block opening local files using window.open().

In order to display local file you must urge user to manually choose file you want them to open. I know that is not the desirable solution but it is how can it work. One of implementation with FileReader is in this answer: How to open a local disk file with JavaScript?

Try use this :

window.open('file:///D:/Examples/file2.extension')

It work for me with a local file

本文标签: javascriptwindowopen for local file pathStack Overflow