What is Clickjacking? and how to Protect Your Webpage from Clickjacking with JavaScript
![]() |
| What is Clickjacking? and how to Protect Your Webpage from Clickjacking with JavaScript |
What is Clickjacking?
Clickjacking, also known as UI redress attack, is a malicious technique where an attacker tricks a user into clicking on something different from what the user perceives, thereby performing actions unbeknownst to them. This can lead to unauthorized access, data theft, or other harmful activities. The term "clickjacking" is a combination of "click" and "hijacking," signifying the hijacking of a user's click.
How Does Clickjacking Work?
Clickjacking typically involves embedding a transparent or opaque iframe over a legitimate web page. The attacker then crafts the iframe in a way that when the user clicks on a visible button or link, they are actually clicking on the hidden content within the iframe. This can lead to unintended actions such as changing account settings, initiating transactions, or granting permissions.
Example of Clickjacking
Consider a scenario where a user is on a trusted website and clicks a button to perform an action, such as liking a social media post. Unbeknownst to the user, an attacker has overlaid an invisible iframe on the page. When the user clicks the button, they are actually clicking on a hidden button within the iframe that performs a different action, such as following a malicious account or enabling a webcam.
Types of Clickjacking Attacks
1. Likejacking
This type of clickjacking involves tricking users into liking a Facebook page or post without their consent. Attackers might use enticing content to lure users into clicking a hidden "Like" button.
2. Cursorjacking
Cursorjacking manipulates the user's cursor to click on unintended elements. The attacker changes the appearance or position of the cursor, making it difficult for users to realize they are clicking on something different from what they see.
3. Filejacking
In a filejacking attack, users are tricked into uploading or downloading files without their knowledge. This can lead to the installation of malware or the exposure of sensitive data.
Consequences of Clickjacking
The consequences of clickjacking can be severe, impacting both users and website owners. Some potential consequences include:
- Unauthorized Actions: Users may unknowingly perform actions such as making purchases, changing account settings, or enabling device features.
- Data Theft: Attackers can gain access to sensitive information, including login credentials and personal data.
- Spread of Malware: Clickjacking can lead to the unintentional installation of malware, compromising user devices.
- Reputation Damage: Websites that fall victim to clickjacking attacks can suffer reputational harm, losing user trust and credibility.
How to Prevent Clickjacking
Preventing clickjacking involves implementing various security measures to protect both users and websites. Here are some effective methods:
1. Content Security Policy (CSP)
The Content Security Policy (CSP) is an HTTP header that helps to prevent clickjacking by specifying which sources are allowed to frame your content. For example:
Content-Security-Policy: frame-ancestors 'self'
This directive ensures that only the same origin can embed your content in a frame.
2. X-Frame-Options Header
The X-Frame-Options header is another HTTP header that helps to protect against clickjacking by controlling whether a browser should be allowed to render a page in a <frame>, <iframe>, <embed>, or <object>. For example:
X-Frame-Options: SAMEORIGIN
This directive ensures that your content can only be framed by pages on the same origin.
3. Frame Busting Scripts
Frame busting scripts are JavaScript codes that prevent your webpage from being loaded inside an iframe. Here’s an example:
<script>
if (top != self) {
top.location.href = self.location.href;
}
</script>
This script checks if the current window is not the topmost window, and if so, redirects the top window to the current URL, effectively breaking out of the iframe.
4. User Awareness and Education
Educating users about the risks of clickjacking and encouraging them to be cautious when clicking on unfamiliar links or buttons can help mitigate the risk. Users should be advised to verify the legitimacy of websites and avoid clicking on suspicious content.
Clickjacking is a serious threat that can lead to unauthorized actions, data theft, and other malicious activities. By understanding how clickjacking works and implementing effective prevention methods such as CSP, X-Frame-Options, frame busting scripts, and user education, you can protect your website and users from falling victim to these attacks. Stay vigilant and proactive in securing your web content to ensure a safe and trustworthy online experience.
Protect Your Webpage from Clickjacking with JavaScript
Clickjacking is a sophisticated and malicious technique that attackers use to trick users into clicking on something different from what they perceive, potentially leading to serious security breaches or data theft. One effective method to defend against clickjacking is by preventing your webpage from being embedded in an iframe from another domain. This technique ensures that users are interacting directly with your website, rather than through an intermediary that could be manipulating their actions. Here’s a step-by-step guide on how to implement this protection using a simple JavaScript code.
The JavaScript Code
Here’s the complete JavaScript code to protect your webpage from being embedded in an unauthorized iframe:
<script>
if (top != self) {
// Check if the current window is not the topmost window
if (document.referrer.indexOf(window.location.host) == -1) {
// Check if the referrer does not match the current host
// Create a style element to hide the body
var style = document.createElement('style');
style.innerHTML = 'body { display: none!important; }';
document.head.appendChild(style);
// Redirect the top window to the URL of the iframe after 1 second
setTimeout(() => {
top.location.href = self.location.href;
}, 1000);
}
}
</script>
Explanation of the Code
1. Check if the page is in an iframe
if (top != self)
This condition checks if the current window (self) is not the topmost window (top). If this is true, it means the page is being loaded inside an iframe. This is the first step in identifying potential clickjacking scenarios.
2. Check the referrer
if (document.referrer.indexOf(window.location.host) == -1)
This condition checks if the referrer (the page that loaded the iframe) does not match the current host. The document.referrer property provides the URI of the page that linked to the current page. By verifying that the referrer does not contain the current host's address, we can detect if the iframe is being loaded from a different domain, which is a common technique in clickjacking attacks.
3. Hide the page content
var style = document.createElement('style');
style.innerHTML = 'body { display: none!important; }';
document.head.appendChild(style);
This part of the code creates a <style> element that hides the body of the document by setting display: none!important;, effectively making the content invisible. This is a defensive measure to ensure that if the page is being improperly loaded in an iframe, the user will not see or interact with any content on the page.
4. Redirect the top window
setTimeout(() => {
top.location.href = self.location.href;
}, 1000);
This sets a timeout to redirect the top window to the URL of the iframe after 1 second. This ensures that the user is taken directly to your webpage, bypassing the iframe. The delay allows the script to execute fully and ensure the redirection occurs smoothly.
Why is Clickjacking Dangerous?
Clickjacking is dangerous because it can lead to unauthorized actions being performed on behalf of the user. For instance, attackers might craft a hidden interface on top of a visible one, causing users to unknowingly click on buttons or links that perform harmful actions. These actions could range from changing settings on a website to performing financial transactions. Protecting your webpage against clickjacking is therefore crucial for maintaining the security and integrity of user interactions.
Implementation in an HTML Document
You can embed the above JavaScript code into your HTML document to protect it. Here’s an example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Iframe Protection</title>
</head>
<body>
<h1>This is a protected page</h1>
<p>If you see this message, you are not viewing this page in an unauthorized iframe.</p>
<script>
if (top != self) {
// Check if the current window is not the topmost window
if (document.referrer.indexOf(window.location.host) == -1) {
// Check if the referrer does not match the current host
// Create a style element to hide the body
var style = document.createElement('style');
style.innerHTML = 'body { display: none!important; }';
document.head.appendChild(style);
// Redirect the top window to the URL of the iframe after 1 second
setTimeout(() => {
top.location.href = self.location.href;
}, 1000);
}
}
</script>
</body>
</html>
Additional Security Measures
While the above method is effective, there are additional security measures you can take to protect your website from clickjacking:
- Content Security Policy (CSP): You can use the Content Security Policy header to control which sites are allowed to frame your content. For example:
Content-Security-Policy: frame-ancestors 'self'. This directive ensures that only your own domain can frame your content. - X-Frame-Options Header: This HTTP header can be used to indicate whether a browser should be allowed to render a page in a
<frame>,<iframe>,<embed>, or<object>. For example:X-Frame-Options: SAMEORIGIN. This prevents your content from being framed by pages from other origins.
Conclusion
By implementing this simple JavaScript code, you can protect your webpage from being embedded in unauthorized iframes, thereby mitigating the risk of clickjacking attacks. This ensures that users interact directly with your page as intended, enhancing both security and user experience. Additionally, consider implementing other security headers like Content Security Policy and X-Frame-Options for a more robust defense strategy.

Join the conversation