Daniel Lemire's blog

, 1 min read

How to make external links exit HTML frames?

Generally, avoiding copy and paste is a great idea whether you are designing a web page or sending people on the moon.

A common problem with the badly constructed web sites relying on HTML frames is that external links are loaded within the frame which poses serious usability issues. A better solution is not to use frames, but sometimes, you are stuck with them. I had an argument recently with some people who insisted they had to add a “target=’_top'” attribute to all external links, in all pages.

Using the DOM API and JavaScript, you can easily add the correct target attribute to all external links without any copy and paste if you follow the convention that external links begin with “http”. Simply add the following within the “head” element of your web page:


<script type="text/javascript">
function externalLinks() {
var anchors = document.getElementsByTagName("a");
for(var i=0; i<anchors.length; i++) {
var anchor = anchors[i];
var myurl = anchor.getAttribute("href");
if( ! myurl) continue;
if(myurl.indexOf("http") == 0) {
anchor.setAttribute("target","_top");
}
}
}
window.onload = externalLinks;
</script>

Of course, this relies on JavaScript being enabled, you might have cross-browser issues, and it adds an overhead to the processing of the page.