How to Download the PDF When the Window Is Closing in JavaScript

14 Aug 20261 minute to read

The JavaScript PDF Viewer can automatically download the loaded PDF document when the browser window is refreshed or closed by handling the before unload event.

Prerequisites

  • Include the JavaScript PDF Viewer script and initialize the viewer instance on the page.
  • Confirm the viewer has finished loading the document before attaching the event handler.

Step 1: Create a working sample by following the getting-started guide: Getting started with JavaScript PDF Viewer.

Step 2: Attach a before unload event handler that prompts the user and calls viewer.download() to download the document. Note: browser behavior for this event varies between browsers and some modern browsers restrict prompts; use this pattern judiciously.

// The event triggers when closing or refreshing the window.
window.onbeforeunload = function (e) {
    var message = 'Do you want to close the page?';
    e = e || window.event;
    // For IE and some older browsers
    if (e) {
        e.returnValue = message;
        // Trigger the viewer download method
        viewer.download();
    }
    // For modern browsers, returning a value is not always required
    return message;
};

View the sample on GitHub: Download PDF before closing or refreshing window sample