March 14, 2023

Preventing Cross-Site Scripting (XSS) Vulnerabilities with Safe href and src URLs

“Don’t let attackers exploit your href and src attributes – learn how to prevent XSS vulnerabilities with safe URLs!”

Cross-site scripting (XSS) is a significant security vulnerability that occurs when attackers inject malicious scripts into web pages viewed by other users. The ultimate goal of an XSS attack is to execute the attacker’s code on the victim’s browser, allowing them to steal sensitive information, hijack user sessions, or perform other malicious actions. One of the common ways that XSS vulnerabilities occur is through the use of href or src attributes in HTML tags, particularly in anchor and iframe tags. Attackers can exploit these attributes to inject their own code into a lightning page, which executes when other users visit the page.

Code Example

For example, consider the following code:  

					<a href="{!}">click</a> 


An attacker can set the value of to a JavaScript URL like this: 



This will result in the following HTML code: 

					<a href="javascript:alert(0000)">click</a> 


When a user clicks on this link, the JavaScript code executes in their browser, giving the attacker unauthorized access to steal user sessions or perform other malicious activities. 

Preventing XSS Attacks:

To prevent XSS attacks that exploit href and src attributes, several options are available for sanitizing these attributes. One of the ways to prevent such attacks is to mark the attribute as private when you set it in your code and do not set it externally. This can help prevent attackers from injecting their own code into the attribute.  

Alternatively, if you cannot mark the attribute as private and must set it in component markup (rather than a custom renderer), you will need to sanitize the attribute yourself. One way to do this is to use a function like the following: 

					sanitizeUrl: function (url) { 

    let tempElement = document.createElement('a'); 
    tempElement.href = url; 

    if (tempElement.protocol === 'https:' || tempElement.protocol === 'http:') { 
        return url; 
    } else { 
        return ''; 


This function creates a temporary anchor element and sets its href attribute to the URL to be sanitized. It then checks the protocol of the URL to ensure that it is either HTTP or HTTPS. If the protocol is valid, the function returns the original URL. If the protocol is invalid, the function returns an empty string. 

By using this function to sanitize href and src attributes in your web applications, you can help prevent XSS attacks and keep your users’ data and sessions safe from attackers. Always ensure that you sanitize input data from external sources before using it in your application to prevent XSS vulnerabilities. 

Share this post:

Discover more articles