Friday, December 01, 2006

Obfuscating email addresses on your web page

Publishing an email address "in clear" on a web page is a bad idea. It just leads to masses of spam. Here's a neat JavaScript solution that gets around the problem. The first step is to assign a JavaScript function to a hyperlink as follows:

<a href="#" onclick="javascript:sendmail();">Send an email</a>

And here's the JavaScript function that creates the email. No need for a form, which is cool:

<script language="javascript">
function sendmail() {
 /*
 we want mailto:info@restofaddress.com
 and here's how we get it...
  */
 var addr = "mailto";
 addr = addr+":";
 addr = addr+"info"+String.fromCharCode(64);
 addr = addr+"restofaddress.com";
 window.location = addr;
}
</script>

You can get more sophisticated. Supposing you want multiple addresses on a page, here's how:

<a href="#" onclick="javascript:sendmail('info', 'restofaddress.com');">
Send an email</a>

The link above passes two arguments to the function below:

<script language="javascript">
function sendmail(part1, part2) {
  /*
 we want mailto:info@restofaddress.com
 and here's how we get it...
 */
 var addr = "mailto:";
 addr = addr+part1+String.fromCharCode(64)+part2;
 window.location = addr;
}
</script>

And don't forget that you can do other things with mailto like adding a subject:

<script language="javascript">
function  sendmail(part1, part2) {
 /*
 we want mailto:info@restofaddress.com
 and here's how we get it...
  */
 var addr = "mailto:";
 addr = addr+part1+String.fromCharCode(64)+part2;
 var subj = "?subject=please send more information";
 window.location = addr+subj;
}
</script>

0 Comments:

Post a Comment

<< Home