DEV Community

Cover image for How To Prevent Spam Bots From Harvesting Your Email Address With JavaScript
irishgeoff22
irishgeoff22

Posted on • Edited on

How To Prevent Spam Bots From Harvesting Your Email Address With JavaScript

Preventing spam bots from harvesting your email address with JavaScript involves implementing measures that make it harder for automated scripts to extract the information. Keep in mind that no method is foolproof, but these steps can help reduce the risk:

  1. Use JavaScript to Generate Email Address: Instead of displaying your email address directly in the HTML markup, use JavaScript to generate it dynamically. This means the actual email address won't be present in the HTML source code, making it more difficult for bots to find.
   <script type="text/javascript">
      // Use JavaScript to generate email address
      var user = "example";
      var domain = "domain.com";
      document.write('<a href="mailto:' + user + '@' + domain + '">' + user + '@' + domain + '</a>');
   </script>
Enter fullscreen mode Exit fullscreen mode

In this example, the email address is generated and displayed using JavaScript.

  1. Obfuscate Email Address: Another approach is to obfuscate the email address within the HTML source code. This involves altering the email address so that it's not easily recognizable by bots, but still understandable by human users.
   <a href="mailto:&#x65;&#x78;&#x61;&#x6d;&#x70;&#x6c;&#x65;&#64;&#x64;&#x6f;&#x6d;&#x61;&#x69;&#x6e;&#x2e;&#x63;&#x6f;&#x6d;">Contact me</a>
Enter fullscreen mode Exit fullscreen mode

Here, the email address characters are represented in hexadecimal Unicode.

  1. Image Replacement: Convert your email address into an image and display it on your website. This makes it difficult for bots to extract the email address directly from the HTML.
   <img src="email-image.jpg" alt="Contact me">
Enter fullscreen mode Exit fullscreen mode

While this method can be effective, it may reduce accessibility for users who rely on screen readers.

  1. JavaScript Encryption Libraries: Consider using JavaScript encryption libraries to encrypt your email address. These libraries can encode the email address in a way that requires JavaScript to decrypt it before displaying.

One such library is CryptoJS. Please note that using encryption adds a layer of complexity and may not be necessary for all situations.

Remember that determined spammers may still find ways to extract email addresses, but by implementing these techniques, you can make it more challenging for automated bots. Additionally, regularly update and adapt your methods to stay ahead of evolving spamming techniques.

Pro Tip: hide email address from spammers behind a form captcha to protect your email address from spam.

Top comments (0)