In order to prevent clickjacking attacks, we can use both server-side headers and JavaScript.
1. For JavaScript, we can use the frame-busting technique to detect if your site is being framed by another website.
Here's an example:
if (top.location != self.location) {
top.location = self.location;
}
This piece of code will ensure that the page is not displayed in a iframe by redirecting the top level window to the current page.
2. However, the modern approach is to use HTTP headers like X-Frame-Options and Content-Security-Policy.
So, if you're not aware of what X-Frame-Options and Content-Security-Policy.
- X-Frame-Options will prevent your website from being embedded in iframes. We can use DENY or SAMEORIGIN in your server response headers.
For example. X-Frame-Options: DENY
- Content-Security-Policy will provide even more controls by specifying where your website can be framed.
For example. Content-Security-Policy: frame-ancestors 'self'
These headers when used additionally with JavaScript ensures that our web application in well-protected from clickjacking attacks