Get links in a new window

I got tired of always including target="_blank" when making links in my posts here in Moveable Type. So I went searching for a way to make this happen automatically. (This was one of the reaasons I wanted to get away from Newspro, in fact). I searched through the support forums on moveabletype.org but only found one tip that seemed to do what I wanted.

You basically add a line that says <base target="_blank"> in the <head> section of your main template. That works fine, but the problem is that it affects every link on the page.  I wanted to have links in just the entries themselves open in a new window.  I looked all over and didn't see a solution that fit, so I hacked up one.

If you're in need of this sort of thing as well, I have a fix (of sorts).  It's kind of a drastic one, too.  But first, the fix.  On or about line 515 of $MTDIR/lib/MT/Template/Context.pm (in the '_hdlr_entry_body' subroutine), add this line:

$text =~ s/<\s*A\s+HREF\s*=\s*(["'])(.*?)\1\s*>/<A HREF="$2" target="_blank">/gi;

That will turn every anchor tag into one which opens in a new window.  As I said, it has drawbacks:

  1. Every author's entries for every blog will get changed.
  2. If you already have a target="..." in a link (like for frames), it'll add another.
  3. Since you've made changes to the source of MT, you have to manually add the change back every time you upgrade.  Changing source like this is somewhat "icky".

You can get around #2 by using a conditional with a regex test.  You could also use another regex right before it to strip any existing target=... stuff, then re-apply the target="_blank"  Not terribly elegant, though.  But since I only have ~100 entries and two authors (who both want the same thing) on my web site, and it's kinda late, the solution works for me.  

I'll likely wind up investigating a more permanent/graceful way to get his done but this works for now...

Comments for: Get links in a new window

Post a comment
Name:


Email Address:


URL:


Comments:


Remember info?