Search code examples
javascriptbrowserdownloadsave

Can you access a Browser's Save As Functionality in Javascript?


I'm creating a webpage, which should be easily downloadable by users.

Ideally, I'd like there to be a button at the bottom of the page which activates the browser's save as function. I'd like to do it this way because not everybody knows how to save a web page.

Is it possible to activate the browser's save as functionality via a button press in Javascript?


Solution

  • I don't believe it's possible to trigger browser's Save As dialog upon click of a button.

    However, it is possible to trigger download of the current page using the download attribute of an a tag.

    Sample code:

    function triggerDownload(url, fileName) {
      const link = document.createElement('a');
      link.href = url;
      link.download = fileName;
      link.click();
    }
    
    // call the above method to trigger download
    triggerDownload('https://<current-page-url>', 'page.html');
    

    The caveat of the above code is that it only downloads HTML and not the accompanying CSS/JS. So, in order to mitigate that, it's probably better to trigger window.print() to allow users to download the whole page as a PDF:

    function triggerDownload() {
      window.print();
    }
    

    There are also libraries you can use to do the PDF conversion (such as jsPDF) without using the print dialog.