Open links into a new window based on the extensions

Thursday, 12 March 2009 16:48 by myro

Immagine a scenario where you need to handle how a browser should open different urls into your site. You need to open every link into a new browser's window except links to documents, to avoid opening a blank window.
Infact, using the attribute 'target' into an anchor: 

<a href=http://www.myrocode.com/document.doc target="_blank" >Open my document</a> 

will open first a new window, and then let you download the file.As you can see  this is not a good solution for this scenario.
Here you can find a simple Javascript that will resolve this kind of problem

 <script type="text/javascript">


function OpenIntoNewWindow(url)
{
    // this are the extensions that will be opened in the current windows
    var fileExtensions = new Array('rtf', 'log', 'txt', 'doc', 'pps', 'ppt', 'xls', 'xml',
                                        'docx', 'xsl', 'xlsx', 'ppt', 'pptx', 'mdb', 'accdb','pdf');
    var match = new Boolean(false);
    for (index in fileExtensions)
    {
        if (endsWith(url.toString().toLowerCase(), fileExtensions[index]))
        {
            // we've found a match!
            match = true;
            break;
        }
    }
    if (match == true)
    {
        window.location.href = url;
    } else window.open(url);
}


function endsWith(testString, endingString) {
    if (endingString.length > testString.length) return false;
    return testString.indexOf(endingString) == (testString.length - endingString.length);
}
</script>
<a style="cursor:pointer" onclick="OpenIntoNewWindow('http://www.myrocode.com/default.aspx');">
     my window html</a>
<br />
<a style="cursor:pointer" onclick="OpenIntoNewWindow('http://www.myrocode.com/SampleDocument.doc');">
     my window Doc</a>

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:   ,
Categories:   Web
Actions:   Bookmark and Share | Permalink | Comments (0) | Comment RSSRSS comment feed
If you consider this post usefull for your purposes, please consider visiting my sponsors to help me out with the myrocode.com maintenance. Thank you.