0
0
HtmlDebug / FixBeginner · 4 min read

How to Prevent iframe Clickjacking: Simple HTML Security Tips

To prevent 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.

html
<!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>
Output
The page loads normally and can be embedded in iframes on any site, allowing clickjacking.
🔧

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 + html
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>
Output
The page cannot be embedded in any iframe, preventing clickjacking.
🛡️

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.

Key Takeaways

Use X-Frame-Options or Content-Security-Policy headers to block unwanted iframe embedding.
Set X-Frame-Options to DENY or SAMEORIGIN to prevent clickjacking.
Test your headers with browser developer tools to ensure protection.
Avoid relying on JavaScript frame busting; use HTTP headers instead.
Keep security headers updated as part of your website deployment.