How to Prevent iframe Clickjacking: Simple HTML Security Tips
iframe clickjacking, use the X-Frame-Options HTTP header set to DENY or SAMEORIGIN, or use the Content-Security-Policy header with frame-ancestors. These headers stop other sites from embedding your page in an iframe and tricking users into clicking hidden elements.Why This Happens
Clickjacking happens when a malicious site loads your page inside an iframe and tricks users into clicking invisible buttons or links. This can cause unwanted actions like changing settings or making purchases without the user knowing.
By default, browsers allow any site to embed your page in an iframe, which opens this risk.
<!DOCTYPE html> <html lang="en"> <head> <title>Vulnerable Page</title> </head> <body> <h1>Welcome to My Site</h1> <button onclick="alert('Clicked!')">Click Me</button> </body> </html>
The Fix
To fix clickjacking, add security headers that tell browsers not to allow your page to be framed by other sites. The X-Frame-Options header can be set to DENY (no framing allowed) or SAMEORIGIN (only your own site can frame it).
Alternatively, use the modern Content-Security-Policy header with frame-ancestors to specify allowed framing sites.
HTTP/1.1 200 OK Content-Type: text/html X-Frame-Options: DENY <!DOCTYPE html> <html lang="en"> <head> <title>Protected Page</title> </head> <body> <h1>Welcome to My Site</h1> <button onclick="alert('Clicked!')">Click Me</button> </body> </html>
Prevention
Always set X-Frame-Options or Content-Security-Policy headers on your server to control framing. Use DENY if you never want your site framed, or SAMEORIGIN if you allow framing only from your own domain.
Test your site with browser developer tools to confirm headers are set. Keep your server and frameworks updated to support these headers.
Related Errors
Other framing-related issues include:
- Mixed Content: Loading HTTP iframes on HTTPS pages can cause warnings.
- Frame Busting Scripts: Older JavaScript methods to prevent framing can be bypassed and are less reliable than headers.