Free Plugin - Force PDFs to load in a new window in Squarespace
More in Plugins, Scripting and Styling
Yesterday a client asked if there was any way to force links to PDFs to download rather than opening up for viewing in the same browser window as their Squarespace site.
If you have access to the web server this is a pretty straightforward task - setting certain properties in .htaccess for Apache web servers(or similar for IIS) will force the PDFs to be downloaded rather than being opened in the web browser's native PDF viewer.
As Squarespace is a hosted service it isn't possible to tinker with server settings - and why should you?
My solution, which appears below, is a plugin that hijacks the click event when a PDF is selected and forces it to open in a new browser window. The PDF still opens within the browser but it leaves your website open in its original window.
The Plugin Code
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script> $('a[href*="pdf"]').click(function(e) { e.preventDefault(); // stop the existing link from firing var documentUrl = $(this).attr("href"); // get the url of the pdf window.open(documentUrl, '_blank'); // open the pdf in a new window/tab }); </script>
You should insert the plugin code into your site's sitewide code injection header. If you're already using jQuery you can omit the first line of the code.