Be the first to write a review
Free - Opening PDFs in a new window with JavaScript
Opening documents such as PDFs in a newwindow should be automated using JavaScript for the following reasons:
- Users will often close the web browser when a PDF is opened, mistakenly believing the document has been opened in Adobe Reader
- The attribute historically used to open a new window, target, has been removed from the HTML 4.01 Strict specification (it's now deprecated)
- Opening a new window is a behaviour and should be moved to the behavioural layer.
Using JavaScript can also be particularly useful when a website is content managed. Rather than having to rely on site editors to remember to open a link to a PDF in a new window the process is handled by a simple JavaScript function.
Check out this fully functioning example to see what we'll create. Check out Advanced Layer Popup if you want to open your PDF in a layer that pops up or Advanced Open Window if you want to create a new window with the press of a button.
Registering an event
The first task is to create an event that occurs when the page has loaded. Rather than trying to execute a function call using <body onload="callfunction()"> within the HTML page we're going to use Simon Willison's addLoadEvent(func). This will allow us to add function calls once the page has loaded.
We'll type the following JavaScript into the .js file (all subsequent code should be entered before this function so the addLoadEvent is last):
function addLoadEvent(func)
{
var oldonload = window.onload;
if (typeof window.onload != 'function')
{
window.onload = func;
} else {
window.onload = function()
{
oldonload();
func();
}
}
}
addLoadEvent(fNewPDFWindows);
The function fNewPDFWindows()
We'll create an empty function in the JavaScript file called fNewPDFWindows. To avoid any JavaScript errors with the script, we also check to see if the command getElementsByTagName is available:
function fNewPDFWindows ()
{
if (!document.getElementsByTagName) return false;
}
The second task is to create an HTML object
collection of any links within the page. The following line gets all links
within the page:
var links = document.getElementsByTagName("a");
We insert this line after the check to see if
getElementsByTagName object method exists as follows:
function fNewPDFWindows ()
{
if (!document.getElementsByTagName) return false;
var links = document.getElementsByTagName("a");
}
The next task is to loop through all of the links and check to see if we want to open any of the links in a new window. If the link is to a PDF document then we'll open it in a new window.