Tagged: button, force download, link
-
AuthorPosts
-
June 13, 2023 at 12:03 am #1410396
Hi, I’m using the button element for a downloadable PDF that currently opens in a new browser window. I’m wanting to have the PDF download to the users PC rather than having it open in a browser window. Is that possible and if so how do I go about doing this.
Thanks
June 13, 2023 at 4:40 am #1410411Hey Snerp,
Thank you for the inquiry.
You may need to manually create a download link using the “a” tag and add the “download” attribute to it.
// https://www.w3schools.com/tags/att_a_download.asp
Best regards,
IsmaelJune 13, 2023 at 9:29 am #1410418Unfortunately, this is not a matter that you can control yourself. Even if the pdf links have this download attribute, the browser settings determine what happens – you can force a download – but the pdf file will open anyway in the browser.
// with file-extension function force_pdf_link_to_download() { ?> <script type="text/javascript"> window.addEventListener("DOMContentLoaded", function () { (function($){ $('a[href$=".pdf"]').each(function() { pdfName = $(this).attr('href').match(/\/([^\/?#]+)[^\/]*$/)[1]; $(this).attr('download', pdfName ).attr('target', '_blank'); }); })(jQuery); }); </script> <?php } add_action('wp_footer', 'force_pdf_link_to_download');
it is not possible to add a download attribute to a link with no value – even if you try that –
texteditor will correct it to:download=""
so the script above will insertdownload="filename.pdf"
Even an entry in the htaccess file does not have to be followed by the browser:
<FilesMatch "\.(?i:pdf)$"> ForceType application/octet-stream Header set Content-Disposition attachment </FilesMatch>
so what could be reached is that the file downloads on click – but it will open in browser tab too.
Perhaps a more skilled programmer than me can force this behaviour – but I think it will be futile, especially since it is supposed to be browser independent.
June 14, 2023 at 4:40 pm #1410610Ok, thank for the excellent support :)
June 14, 2023 at 8:03 pm #1410634 -
AuthorPosts
- You must be logged in to reply to this topic.