Programming

Protecting Email Addresses from Scrapers with JavaScript or jQuery

1 minute read

This post is from February 2012. The screenshots show the interface as it was then; today it looks slightly different in places.

If you publish your email address or those of others simply as HTML code, there is a risk that the addresses will be read automatically by scripts for the purpose of using them as recipients for spam. There are several more or less effective ways to make the addresses visible to website visitors while making automated reading more difficult.

One of these methods is to clear the address of unique features such as @ (as every email address is known to have exactly one @) or . (as a separator between the domain and TLD) by replacing these characters with markers and then swapping them with the correct characters at runtime.

So, instead of writing in the HTML source code
<a href=”mailto:mailname@domain.tld”>mailname@domain.tld</a>
we write
<span class=”amailto”>mailname at domain dot tld</span>
JavaScript (jQuery):
$(document).ready(function(){
  var at = / at /;
  var dot = / dot /g;
  $(“span.amailto”).each(function(){
    var addr = $(this).text().replace(at,”@”).replace(dot,”.”);
    $(this).after(““+ addr +”“);
    $(this).remove();
  });
});