Archive

Archive for the ‘pdf’ Category

Fix for initial opening pdf in new Internet Explorer (6-8) window problem

February 9, 2012 4 comments

Problem:
In a recent project I am working on I need to allow user to open their documents (in PDF format, hosted in a different server with different domain) in a new window. This seems to be a pretty straight-forward task as all I need is window.open (url is not hard-coded in the href as user need to get authenticated with the local server and get the token that will be used to access the document) but when it comes to Internet Explorer I got stuck with a weird problem. For versions 6-8, the first click on the pdf view link since the initial launch of IE browser always results in a blank window. User needs to either press F5 on the popped-up window click the view link (same or different) again get PDF loaded. The following code works without issues in all browsers except IE6-8:

HTML:

<a href="void(0)" onclick="javascript:opendoc('abc123')">View Document</a>

JS:

function opendoc(docid) {
    // skipping code getting token via ajax call
    var url="https://remote.host.url/somepath&docid="+docid+"&token="+token;
    var win=window.open( url, 'newwindow' );
}

Through a lot of trial and errors which include the followings:

  • refresh the new popup after some time
  • close the popup then open it again after some delay
  • server-side redirect
  • pdfobject
  • using embed tag

I found a workaround that actually works. Basically the same url got opened twice (only for the initial loading after launching browser) with 5 seconds apart if client browser is IE6-8. Note: The last two methods fail as well. I think it has something to do with the document.domain setting in the parent window.

Solution:

// this variable is to store if the double loading trick has been done
var first_clicked=0;
function opendoc(docid) {
    // skipping code getting token via ajax call
    var url="https://remote.host.url/somepath?docid="+docid+"&token="+token;
    var win=window.open( url, 'newwindow' );
    // using jQuery to do browser testing, feel free to use other methods
    if(!first_clicked && $.browser.msie && $.browser.version.substr(0,1)<'9') {
        setTimeout( function() {
            win=window.open( url, 'newwindow' );
        }, 5000 );
        // adjust the time to be shorter but be sure to
        // do enough tests as I found if the value is too low (300, 500, 1000 for example) it won't work either
        // it may have something to do with the connection speed to remote server
        
        first_clicked=1; // set to 1 so sequential clicks open the link only once
    }
}

This doesn’t seem to be a perfect fix as it still requires user to wait for a few seconds before the first result can be viewed but it’s better than leaving user in the dark or asking them to press F5 in order fix the problem.