In order to protect our application against clickjacking attacks in JavaScript, we can combine JavaScript detection techniques with HTTP security headers for a strong defense.
1. JavaScript Frame-Busting Code
We can use JavaScript to check if our app is being loaded within an iframe and prevent it if necessary:
if (window.top !== window.self) {
window.top.location = window.self.location;
}
Now this piece of code will check if the current window is not the topmost window. If it detects framing, it forces the top window to navigate to the current URL, effectively "busting" the frame.
2. X-Frame-Options HTTP Header
We can set this HTTP header to prevent our pages from being embedded in iframes on other domains:
• DENY: Completely blocks the page from being framed.
X-Frame-Options: DENY
• SAMEORIGIN: Allows framing only if it's from the same origin as the page.
We can set these header at the server-side to ensure our page can't be iframed in incompatible browsers.
3. Content Security Policy (CSP) Frame-Ancestors Directive
We can use the CSP frame-ancestors directive to define which domains are allowed to embed our content:
Content-Security-Policy: frame-ancestors 'self'
Over here, the frame-ancestors 'self' setting only allows our own domain to frame the page, adding a layer of protection on compatible browsers.
4. JS-Based Visual Checks
You can also consider implementing visual checks to ensure users are aware of the framing if it's necessary for specific scenarios.
- Either we can detect overlays by monitoring changes in window dimensions.
- Or we can use CSS to display a border or visual cue around the content if it's embedded.
5. Preventing Framing in Legacy Browsers
There are some older browsers which might not support CSP or X-Frame-Options, so we can consider frame-busting scripts as a fallback. We can include these on every page for broader coverage.