Is it possible to have regular anchor tags pointing to files that open a dialog for saving the file? Like a web browser would.
For example:
<a download href="documents/somefile.pdf">Download</a>
And having that anchor-tag triggering a Save file-dialog on click?
I've tried using file://absolute-path-to-the-dir/documents/somefile.pdf
and it wants to open the file in the application rather than download it.
Update: In a later version of Electron than I used when I wrote this question the behaviour is as I want it to be, a window opens that asks the user to save the file.
However, in the case of external links and wanting to keep the Electron window only for internal links and open the external ones in the default OS choice, the answer by Joshua Smith can do exactly that.
In script you can use the save file dialog by using the dialog module:
var fs = require('fs');
var dialog = require('dialog');
dialog.showSaveDialog(options, function (filePath) {
fs.writeFile(filePath, pdfContents, function (err) {
if(err) console.error(err);
});
});
Here is the documentation:
https://github.com/atom/electron/blob/master/docs/api/dialog.md#dialogshowsavedialogbrowserwindow-options-callback
What I'm doing is two-fold.
mainWindow.webContents.on('new-window', function(event, url) {
event.preventDefault();
console.log("Handing off to O/S: "+url);
shell.openExternal(url);
});
That is there so that whenever a page in my app wants to open a new window, that'll happen in an actual browser. This is also good for opening PDFs and such.
Then I just make sure that any download links use target=_blank or window.open() and the download will happen in the user's browser.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With