allBlogsList

How to specify the link attribute to open on a new window programmatically

I am sure you must be surprised with the topic here. We all know how to open a link on a new window using the "Target" attribute, and we can set this up on the Sitecore field level when using the "General Link" field. In other words, along with the field value we can also specify the target attribute value in there. But what if there is a situation where we have thousands and thousands of such sitecore items with various values for "General Link" pointing to Sitecore media file of type say "pdf" and you wish to now change those ("General Link") values to indicate the Target to open on a new window. Earlier it was specified with the default same window.

There are three ways to go about this:

1- Write a sitecore powershell script to modify all such "general link" values to specify the "Target" value to "_blank".
2- Look through all the code in our solution where we are rendering the "general link" using the "@Html.Sitecore().Field" and overwrite the "Target" value.
3- Overwrite the way such link fields are rendered using a Sitecore pipeline, such that the Target value is always set as "_blank".

Although all three routes specified are ok but as you can understand, are not very straightforward. Comes out that there is a very easy third approach using jquery that is not only a one-liner but also extremely easy to inject through code.

What I did was, put in the following code in my default layout view cshtml file and that did it.

<script>  
  
        $(document).ready(function () {  
  
            // force PDF Files to open in new window  
            if (!$('a\[href$=".pdf"\]').attr('target')) {  
                $('a\[href$=".pdf"\]').attr('target', '\_blank');  
            }  
  
        });  
  
</script>

So, I look for "pdf" anchor elements and if "target" is not specified, then I add it with the "_blank" value.