A Simple JavaScript Code to Easily Detect Bots 🤖 on Your Website

← Prev

Not all bots are created equal, some can be useful, while others can be harmful to your website. Malicious or spammy bots often distort your analytics data, especially in tools like Google Analytics (or GA 4), by inflating traffic or triggering false events. I encountered similar problems and, rather than relying on third-party bot detection solutions, I decided to create a lightweight JavaScript script to distinguish between human users and automated bots.

So, here's a simple JavaScript bot 🤖 detection snippet you can embed into a webpage. It checks for human interaction like mouse movement or keypress, and flags the session as suspicious if no activity is detected within a short time window.

<!DOCTYPE html>
<html>
<head>
  <title>Bot Detection Test</title>
</head>
<body>
  <h1>Hello there...</h1>
  <p>Just making sure you're not a robot 🕵️‍♀️</p>
</body>
<script>
  let isHuman = false;

  // Listen for basic human interactions.
  window.addEventListener('mousemove', () => isHuman = true);
  window.addEventListener('keydown', () => isHuman = true);
  window.addEventListener('scroll', () => isHuman = true);

  // Trigger check after 5 seconds.
  setTimeout(() => {
    if (!isHuman) {
      alert ("🤖 It is Possibly a bot.");

      // Prepare time and date stamp.
      const timestamp = new Date();
      let data = `
        Bot: ${'true'}
        detectedAt: ${timestamp} 
        pageURl: ${window.location.href}`;

      // Convert the text to BLOB.
      const textToBLOB = new Blob([data], { type: 'text/plain' });
      const sFileName = 'log_bot_details.txt';	   // The file to save the data.
      
      // Save the .txt file with the data.
      let newLink = document.createElement("a");
      newLink.download = sFileName;

      if (window.webkitURL != null) {
        newLink.href = window.webkitURL.createObjectURL(textToBLOB);
      }
      else {
        newLink.href = window.URL.createObjectURL(textToBLOB);
        newLink.style.display = "none";
        document.body.appendChild(newLink);
      }

      newLink.click(); 
      
    } else {
      console.log("User seems human.");
    }
  }, 5000);
</script>
</html>
Try it

👉 There are three event listeners that detect common human activity.

1) mousemove: detects if the mouse moves

2) keydown: detects any keyboard input

3) scroll: detects if the user scrolls the page. If any of these occur, isHuman gets set to true.

👉 The setTimeout() function delays the bot check by 5 seconds after the page loads.

Note: The 5 seconds delay is important, because Google Analytics (especially with certain configurations like engagement-based metrics in GA4) treats sessions as bounces if the user doesn't interact or stay long enough.

GA4 considers a session engaged only if one or more of the following occurs:

* Session lasts 10 seconds or longer
* There’s a conversion event
* Multiple pages are viewed

👉 If no interaction was recorded or if the condition is !isHuman, it shows an alert stating bot-like behavior. In-addition, it logs the bot activity in a text file.

If you want, you can send bot details to the server for analysis using a simple script like this:

// Send this info to your server for analysis.
fetch('bot-details.json', { 
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    }, 
    body: JSON.stringify({ bot: true,
        detectedAt: timestamp,
        pageURL: window.location.href 
    }) 
});

Conclusion

This is a basic form of behavioral bot detection. While it won’t catch every bot (especially more advanced headless browsers that mimic user input), it’s a lightweight and useful strategy for filtering out basic automation.

← Previous