1. Home
  2. Knowledge Base
  3. Document Library Pro
  4. Advanced Usage

Code snippet - Force the user's browser to download the file

The download links in Document Library Pro will generally download the file directly to the user's computer, but this depends on the settings in the user's browser. For example, some browsers may be set to open PDF files in the browser with a second download button, instead of downloading them directly.

The following code snippet will force the user's browser to download the file, overriding the browser's usual behavior. Add it to your site if you want to encourage downloads rather than in-browser viewing.

The snippet adds the download attribute to all download links in your document library. This instructs most modern browsers to download the file to the user's computer instead of opening it in the browser (e.g. for PDFs). It applies to all file types and also supports dynamically loaded content. However, this behavior depends on the browser, file type, and server configuration. Some browsers may still open certain file types (like PDFs) inline, especially if the server instructs them to do so.

This code is aimed at developers and you can check out our article on how to use code snippets, or ask your developer to add it for you. We also provide a customizations service.

jQuery(function($) {
$(document).ready(function() {
    function addDownloadAttribute(element) {
        if (element) {
            $(element).find('a.dlp-download-link').attr('download', '')
        } else {
            $('.dlp-download-link').attr('download', '')
        }
    }
    
    addDownloadAttribute()
    
    const observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.addedNodes && mutation.addedNodes.length > 0) {
                for (let i = 0; i < mutation.addedNodes.length; i++) {
                    const node = mutation.addedNodes[i]
                    if (node.nodeType === 1) {
                        addDownloadAttribute(node)
                    }
                }
            }
        })
    })
    
    observer.observe(document.body, { 
        childList: true,
        subtree: true 
    })
    
    $(document).on('mousedown', 'a.dlp-download-link', function() {
        $(this).attr('download', '')
    })
})
})

Related Articles

If searching the knowledge base hasn't answered your question, please contact support.