Archive for the 'JavaScript' Category

Fight Spam with jQuery!

OK, maybe title should actually be “Prevent email address harvesting with jQuery”. But anyway - I came up with a technique for our company web site today which will hopefully prevent some of the email addresses that we publish being picked up by email address-harvesting bots. The idea is that an email address is put on the website using the following obfuscation:

<span class='email'>joebloggs [at] example [dot] com</span>

And then transformed by JavaScript into:

<a href='mailto:joebloggs@example.com'>joebloggs@example.com</a>

It’s a progressive enhancement in that the content is still quite legible by people with JavaScript turned off. Here’s the jQuery script that does it:

$(function() {
   $('.email').each(function() {
      var $email = $(this);
      var address = $email.text().replace(/\s*\[at\]\s*/, '@')
                                 .replace(/\s*\[dot\]\s*/g, '.');
      $email.html('<a href="mailto:' + address + '">'+ address +'</a>');
   });
});

I’m perhaps being naïve about how email addresses are collected these days, and maybe embedding email addresses in images is a better approach - but this was quick and simple and worth a try.

IE 6 bug causes jQuery globalEval error

UPDATE: this is fixed in jQuery 1.2.6 and later, see ticket #2709.

After upgrading our code base to use the latest jQuery 1.2.3 (previously we were using 1.2.1) our testers discovered a quite ridiculous bug in IE 6 that caused jQuery to fail (IE 7 is fine, which is why we didn’t experience it development). The issue manifested itself as the script error message “Problems with this web page might prevent it from being displayed properly…

Line: 24
Char: 76
Error: Invalid Argument
Code: 0
...

…and various document.onready handlers not running.

Of course line 24, char 26 doesn’t really help much because IE always seems to get this a few lines out of whack and with the minified version of jQuery it would be way out. So I replaced the minified version jQuery.js with the uncompressed version, cleared the browser cache and re-visited the web app in IE 6. This then gave line 659, char 4 as the offending location:

image

After whacking in a several alert()s in the lines in the vicinity of 659, it turns out the issue is with head.removeChild(script) in the globalEval function, 4 lines up. Obviously.

So, why was head.removeChild failing? I put the following debug code in:

alert(head.tagName) // displays "HEAD" as expected
alert(script.parentNode.tagName) // displays "BASE" !!!

So, it transpires that our pages having a <base> tag within the <head> contributes to the issue. IE 6 seems to get totally confused as to the structure of the document HEAD when there’s a self-closing or unclosed BASE tag. BASE tags I suppose are quite rare and this is probably why this issue doesn’t appear to be commonplace. (The BASE tag is in there for legacy reasons in our code, but they’re also quite useful when you save the source of HTML pages they still pick up images and script from the originating server which is handy for debugging automatically-generated HTML.)

So, before, the offending base tag looked something like this:

<base href='http://example.com/blah' />

After some experimentation it appears IE6 doesn’t exhibit its odd behaviour if you do this instead:

<base href='http://example.com/blah'></base>

Job done.

Update: Chris Venus comments about the reason for the weird behaviour in IE6 and earlier. Previously <base> was interpreted as a container, which could appear multiple times in a document: different sections within the page could have different bases, so would logically end up wrapped within each <base> (now there’s a feature everybody wanted, right?). Because of this, <head> got treated as a “section” of the document and elements added to it ended up as children of any <base> it contained rather than siblings. See IEBlog: All your <base> are belong to us.

Backing up an Exchange Mailbox to a PST file

I’ve never trusted Exchange Server backup 100% ever since Exchange 2000, following a service pack, refused to restore backups from the non-service packed version (yes honestly).

So I’ve always had a 2-pronged approach to backup, do the usual monolithic backup using NTBackup, but also have mailboxes individually backed up as plain old PST files, which Outlook can easily mount to make it easier to do partial restores. In the past I’ve used ExMerge to do this, but it’s a becoming a bit neglected and is very clunky to script: it’s a Windows app (rather than a console app) that’s driven by an INI file.

Anyway, whilst doing some integration work against Exchange for a client I came across Dmitry Streblechenko’s superb Redemption Data Objects library. It is a really easy to use COM wrapper around Extended MAPI - a super-charged version of Collaboration Data Objects (CDO).

Honestly I really can’t understand why Microsoft didn’t ship a library like this (or improve CDO) rather than expecting you to write gnarly C++/COM/MAPI code to do what this library allows you to do easily from .NET code or a script. The Exchange API goalposts move from one release to the next: “Use the M: drive! No, use WebDAV! No, use ExOLEDB!… No, use Web Services!” with the only constant being good old MAPI.

Anyway - here’s part of our PST backup script - it relies on the Redemption Data Objects (RDO) COM DLL being registered. The free developer version pops up a prompt once when you RegSvr32 it, the royalty-free redistributable version is a incredibly reasonable $199.99. RDO relies on MAPI being installed, so grab it here if it’s not present on your system.

/* BackupPst.js */

// e.g. copyMailboxToPst(
           "EXCH01",
           "FredB",
           "c:\\backups\\fredb.pst",
           "FredB backup")

function copyMailboxToPst(serverName, userName, pstFile, pstName)
{
  var session = new ActiveXObject("Redemption.RDOSession");
  session.LogonExchangeMailbox(userName, serverName);
  WScript.Echo("Logged on to " + session.ExchangeMailboxServerName);

  var mailbox =  session.Stores.DefaultStore;
  var pstStore = session.Stores.AddPSTStore(pstFile, 1, pstName);

  try
  {
    WScript.Echo("Opened " + mailbox.IPMRootFolder.FolderPath);
  }
  catch(err)
  {
    WScript.Echo("Error opening mailbox '" + userName
       + "' (access denied?). " + err.description);
    return;
  }

  foreach(mailbox.IPMRootFolder.Folders, function(folder)
  {
    WScript.Echo(" * " + folder.Name);
    folder.CopyTo(pstStore.IPMRootFolder);
  });

  pstStore.Remove();
}

// Utility to allow enumeration of COM collections
function foreach(collection, fn)
{
  for(var e = new Enumerator(collection); !e.atEnd(); e.moveNext())
  {
    if(fn(e.item()))
      break;
  }
}

This could be further improved for incremental backups by using RDO’s newly introduced wrappers to the “Incremental Change Synchronization” API where you can use the same syncing technology that Outlook’s cached Exchange mode uses!