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?
-
"it seems like window.open() function ignore the first /" — It doesn't. You need to provide a [mcve]. 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 Jan 11 '18 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 Jan 11 '18 at 16:53
3 Answers
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.

- 914,110
- 126
- 1,211
- 1,335
-
Yes, indeed that many browsers block file:///. Yes, i need absolute path in order to download from browser. If it is started without initial "/", the site can't be reached error will be thrown. Therefore, i am wondering, is that window.open method ignore the initial / – Brian Ruchiadi Jan 11 '18 at 17:00
-
"is that window.open method ignore the initial /" — No. It doesn't. It resolves relative URLs as normal. – Quentin Jan 12 '18 at 10:13
Try use this :
window.open('file:///D:/Examples/file2.extension')
It work for me with a local file

- 2,620
- 1
- 10
- 22
-
2I have tried this approach, however it seems like most of the browser block this approach. – Brian Ruchiadi Jan 11 '18 at 17:04
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?

- 9,104
- 5
- 56
- 60