Thursday, September 06, 2007

Make Selected Links in a Links List Open in a New Window


One of the questions that comes up frequently in our classes is, "How can I make some of my links in a Links List open in a new window?" I usually explain how I would accomplish this using JavaScript. I've answered this question so often now that I guess it's time to post the solution here on the blog.

When you add a link to your SharePoint navigation, or in a Summary Link Web Part, it gives you the option to, "Open link in new window." However, the standard Links list, doesn't give you this option. Many users seem to want it though.

The first part of my solution involves training your end-users to add something extra onto links that they want to open in a new window. I like to have them add. "#openinnewwindow". There is a two-fold reason for this. One, it's fairly easy for most users to remember once they've used it a couple times. Two, if the JavaScript code isn't in place, it doesn't cause any errors when a user clicks on the link--it will just open in the same window as normal (unless there is a named anchor on the target page named "openinnewwindow", which is highly unlikely. :) )



The second part of my solution is the JavaScript code that makes this work. Here is the code. It can be placed into the source of a Content Editor web part, or even added to your master page.

Note: In the code example below, replace the square brackets around the SCRIPT tags with angle brackets. If I included the angle brackets, the browser tried to execute the code. :(

[script language="JavaScript"]

//add an entry to the _spBodyOnLoadFunctionNames array

//so that our function will run on the pageLoad event
_spBodyOnLoadFunctionNames.push("rewriteLinks");



function rewriteLinks() {

     //create an array to store all the anchor elements in
the page

     var anchors = document.getElementsByTagName("a");

     //loop through the array

     for (var x=0; x<anchors.length; x++) {

     //does this anchor element contain #openinnewwindow?

          if (anchors[x].outerHTML.indexOf('#openinnewwindow')>0)
{

              
//store the HTML for this anchor element

               
oldText = anchors[x].outerHTML;

              
//rewrite the URL to remove our test text and add a target instead

              
newText = oldText.replace(/#openinnewwindow/,'" target="_blank');

              
//write the HTML back to the browser

              
anchors[x].outerHTML = newText;

         
}

    
}
}

[/script]





That's all you need to do make this work!



For all you code junkies, I think the comments in the code explain well enough what is going on. Let me know if you have questions.

41 comments:

Anonymous said...

Great code ! thanks

Anonymous said...

Can not get it to work!
I have added the script to the top of the default.master file and put the #openinnewwindow at teh end of the link but it appear that the script does not run. I know this because when i hover over the link it still has #openinnewwindow after it.
Can anyone suggest what may be wrong?

Anonymous said...

Can you please tell me what is the right place for the javascript code? I tried adding the code in the content editor web part on the links page. Its not working :( your reply will be really helpful. Thanks!

- Gator said...

Will this work in WSS V3? I added the code to the CEWP on the home page, and added the #openinnewwindow to the end of a URL listed in the Links web part. No luck though... site still comes up in the same window.

- Gator said...

Will this work in WSS V3? I added the code to a CEWP and added the #openinnewwindow to one of the links in the link list. (Link view & CEWP are on the same page)

No luck though... am I missing something? (and yes, did change the brackets for the script code).

Anonymous said...

Thanks for this info - question: I cant seem to get this to work for a blog Post that has a link to a PDF...is it possible? I tried adding the code by way of the HTML source editor and no luck - looks like the code doest stick. Thoughts?

Anonymous said...

Can't seem to get this to work. I've replaced your code with correct angle brackets, placed it in a CE Web part on a MOSS site, added the #openinnewwindow at the endo of the link URL, but it still opens in the same page.

Anonymous said...

If you are having trouble with copying and pasting this code, please notice the portion of the comments that are wrapped.

//create an array to store all the anchor elements in
the page

Although this snippet shows multiple words that are wrapped,it is only the "the page" in the code you copied and pasted that needs attention.

The words "the page" do not have any comment delimiters preceding them, so they are being treated as part of the code, rendering it non-functional.

Just place "//" without the quotes before the words "the page", and then try it again in Content Editor Web Part.

You can check whether the code is working or not by doing a view source, and seeing if the word "target" now accompanies your links.

If the source code still has "#openinnewwindow" (or whatever you chose) present, then the HTML has not been re-written and there is something else wrong with your code.

Anonymous said...

This works really well! Is there a way to open a link in a new tab for those using IE7?

Ricky Spears said...

@shanene - Sorry, but I'm not aware of any way to control IE7 tabs from JavaScript.

sree said...

Thanks Ricky it worked for me.Thanks a lot. i have one question though can we disable the new item (content type) of a list after a particular person posted one though javascript?

Ricky Spears said...

@Sree - That's quite a challenge, but may be doable. It's not something that I can devote time to writing right now. If I was going to write this, I would probably have my JavaScript look for the User's name on the page (assuming that it appeared on the page in the Created By column.) Then if it did appear on the page, the JavaScript would re-write the menu. You can view the code from OWS.js to see how the menu is created. I don't know that this will work, but it may get you started looking in the right direction. Good luck!

Anonymous said...

Is it possible to enclose this functionality in a site or site collection feature? I thought about something like masterpage customization but using templates, not modifying masterpage's code?

Ricky Spears said...

Obieg - It's not something that I can currently go into here, but I don't see any reason why you couldn't do this.

Anonymous said...

Hi
I am trying to get this to work to a link on the quick launch bar.
I tried inserting the code in the source code of the default master page, but it did not work. I am not a programmer and am concerned I put the code in the wrong place, could you please advise where the code needs to be inserted in the html code.
Thanks
Paul

Ricky Spears said...

Paul - I have successfully added this to a master page. I placed the code just before the closing HEAD tag. You will need to make sure that you change the square brackets around the SCRIPT tags to angle brackets. I also noticed that one of the comment lines wrapped when I copied and pasted it--I had to move that comment to al be on a single line.

Having said that, you don't really need this solution to make an item in the Quick Launch Bar of Top Link Bar open in a new window. When you add the link in the Modifiy Navigation page, you can check the box to "Open link in new window."

Anonymous said...

This code works - but the instruction you posted is lacking. If you are going to use this JS code on the LINKS - then you have to add a content editor web part to the page, edit the content editor web part and put the js into the content editor web part. I wrote a procedure with screen shots.

Ricky Spears said...

Anonymous - Care to post a link to your post with the screenshots?

Jeanne Doney Ritterson said...

Thanks for the easy fix - I am working with a group of co-workers to set up a standard way that we store references as a subject matter expert -- they are not all going to go in and redo their html code. Some times a not so elegant fix is the best. Glad you offered both

Unknown said...

Excellent Solution. Thanks for the post.

Chiem said...

is this solution not supposed to work with firefox??? i got it to work in IE, but not firefox...any help will be much appreciated.

Anonymous said...

it works at wss 3.0 sp2.
Look the post from wmhogg!
Thanks

Anonymous said...

Thanks .. worked great..

SteFetS said...

Works great.
Here is the code if you want to open in a new windows without toolbars
//does this anchor element contain #notoolbar?
if (anchors[x].outerHTML.indexOf('#notoolbar')>0) {

//store the HTML for this anchor element
oldText = anchors[x].outerHTML;
//alert(oldText);


//rewrite the URL to remove our test text and add a target instead
newText = oldText.replace(/#notoolbar/,'" onclick="return popup(this);');
//alert(newText);

//write the HTML back to the browser
anchors[x].outerHTML = newText;

}


}
}

function popup(mylink) {

if (! window.focus)return true;
var href;
if (typeof(mylink) == 'string')
href=mylink;
else
href=mylink.href;
window.open(href, 'SharePoint', 'width=1200,height=850,toolbar=no,scrollbars=no');
return false;
}

Webman09 said...

Thanks...this works great. However, i've noticed if I use this script on a page with "Group by" enabled it does not work. Any ideas on how to correct this?

RobertRFreeman said...

I created a server-side only solution for this using an OpenInNewWindow Yes/No column and my HtmlFilter tool.

http://rrfreeman.blogspot.com/2009/11/my-links-sharepoint-list-web-part-mods.html

Unknown said...

The code works well except that now everything opens in a new window, regardless of whether or not it has the #openinnewwindow tag or not. Suggestions? Running MOSS 2007 Enterprise.

Ricky Spears said...

Jeff - That's really odd. I can't see any reason this would happen unless the IF statement that checks for the presence of #OPENINNEWWINDOW isn't firing for some reason. I would check for any types (maybe copy and paste it in fresh again) or check for any conflicts in the variable names used in this script with the variable names used in any other scripts that run on that same page. Good luck!

Unknown said...

I am trying to use this on a page that has a page viewer webpart. The page viewer web part references a word document with numerous links to pdfs, other word docs, excel docs, and external links, but when I click on a link, it does not open in a new window.

I applied to to the page, within a CEWP and changed the reference to http://mysite/mypath instead of #openinnewbrowser, but no luck.

Any ideas?

Unknown said...

Thanks for the post, it was a helpful start.

We tweaked the originally posted javascript snippet and came up with this. It's simply adding a [target] attribute, and removing the '#openinnewwindow' string from the existing [href] attribute.

*Remember (as noted above) replace the square brackets '[]' with angle brackets '<>' around the opening and closing script tags.


[script language="JavaScript"]

_spBodyOnLoadFunctionNames.push("rewriteLinks");

function rewriteLinks() {
//create an array to store all
var anchors = document.getElementsByTagName("a");

//loop through the array
for (var x=0; x0) {
//add the [target] attribute and rewrite the [href] attribute
anchors[x].target = "_blank";
anchors[x].href = anchors[x].href.replace(/#openinnewwindow/,'');
}
}
}
[/script]

Unknown said...

Some of the script was stripped out in my previous post. I will attempt to post it again in this post.

<script language="JavaScript">
_spBodyOnLoadFunctionNames.push("rewriteLinks");

function rewriteLinks() {
//create an array to store all
var anchors = document.getElementsByTagName("a");

//loop through the array
for (var x=0; x<anchors.length; x++) {
//check to see if the current anchor element contain #openinnewwindow
if (anchors[x].outerHTML.indexOf('#openinnewwindow')>0) {
//add the [target] attribute and rewrite the [href] attribute
anchors[x].target = "_blank";
anchors[x].href = anchors[x].href.replace(/#openinnewwindow/,'');
}
}
}
</script>


If all else fails I've posted here as well: http://www.sharepointlessonslearned.com/blogs/blog1.php/2010/04/28/open-link-list-items-in-new-window

Ricky Spears said...

Doug - Thanks for the enhancement and for sharing it!

saxy46 said...

Firefox doesn't seem to support the outerHTML.indexOf code so this won't work in Firefox. Any idea how to get it to work?

Unknown said...

Does anyone know how I would edit the following code to set the size of the new window to a 640 x 480 resolution? Thanks, Dan

[script language="JavaScript"]

_spBodyOnLoadFunctionNames.push("rewriteLinks");



function rewriteLinks() {

//create an array to store all

var anchors = document.getElementsByTagName("a");



//loop through the array

for (var x=0; x0) {

//add the [target] attribute and rewrite the [href] attribute

anchors[x].target = "_blank";

anchors[x].href = anchors[x].href.replace(/#openinnewwindow/,'');

}

}

}

[/script]

Ricky Spears said...

dan - You're probably going to have to change the entire link from a direct link to a web page to a link to another JavaScript function that is capable of setting the window size. Here is a tutorial that might help get you started:
http://www.javascript-coder.com/window-popup/javascript-window-open.phtml

Cowgirl Kendra said...

Thanks! I really appreciate you taking the time to share this info and post it in a public place. The code worked great (copied it from your second attempt - where you indidcated that the first post may have stripped out some characters). I added it to my master page just before the /Head tag. Worked like a charm.

Mandeep said...

I am a newbie to Sharepoint, and I respect the contributors of this blog. Only One thing came to my mind while I was going through the suggested pieces of code and the author's solution. Don't you think it is unfair to ask the end user to remember to put #openinnewwindow after every link. And for all those experts to have agreed to this solution, I have a question.

If you are trying to find the indexOf(#openinnewwindow), why can one not look up the indexOf(http) , and if its there add the target. And you don't need the next line of code to replace the #openinnewwidnow.

This is obviously when all links are external and will have the (http) which in most cases and scenarios is true.

I am sorry if this hurts anyone, and I look forward to any feedback/comments on this approach. Being a newbie I may be overlooking something which will nto work ideally with this solution. Please feel free to add your valuable input on my comment.

Many Thanks
Mandeep

Ricky Spears said...

Mandeep - The reason I chose to have users add the #openinnewwindow, is it's the easiest way to control which links open in a new window and which ones don't. You certainly don't want every link on the page to open in a new window. :-)

GlobalWhisperer said...

Someone mentioned this would not work with Group By enabled.. I found the same problem.... the anchors are not loaded right away with the link list webpart I was using, so they were never rewritten. I got around this by attaching our rewrite links function to a click event like so:

$('.ms-vb2 a').live("click",function(){
rewriteLinks();

});

GlobalWhisperer said...

Someone mentioned this would not work with "group by" enabled. I had the same issue - the anchors aren't there on page load.. so nothing to rewrite. I got around this also attaching the function to a click event for anchor tags in the webpart.

$('.ms-vb2 a').live("click",function(){
rewriteLinks();

});

Gene said...

I have the Group By issue as well. The above recommendation does not work for me for some reason. Below is what I have (ignore the square brackets):


[script language="JavaScript"]

$('.ms-vb2 a').live("click",function(){
rewriteLinks();

});

function rewriteLinks() {
var anchors = document.getElementsByTagName("a");
for (var x=0; x0)
{

oldText = anchors[x].outerHTML;
newText = oldText.replace(/#openinnewwindow/,'" target="_blank');

anchors[x].outerHTML = newText;

}
}
}

[/script]