I am having trouble adding X-Frame-Options
header to a simple HTML file.
Is there any way to do it using JavaScript?
I am having trouble adding X-Frame-Options
header to a simple HTML file.
Is there any way to do it using JavaScript?
X-Frame-Options
is an HTTP header. As such, it's not part of HTML and can't be set inside an HTML document.
One reason why it's an HTTP header only is that clients should be able to decide if the document is allowed to be embedded in a frame before parsing the HTML code.
Hence, you can't achieve that by editing the file but you need to modify the server's HTTP response. Typically, this is done in the settings provided by the web server software or with a server-side language.
E.g., a setting in Apache could look like this:
Header always append X-Frame-Options DENY
Or, in PHP you could set the header like that:
<?php header('X-Frame-Options: DENY'); ?>
Note that there is a more modern CSP equivalent frame-ancestors
. But while some CSP policies can be set as <meta>
tags, that's not possible here. This does not work:
<head>
<!-- This does *not* work! -->
<meta http-equiv="Content-Security-Policy" content="frame-ancestors 'none'">
</head>
Also have a look at the Clickjacking Defense Cheat Sheet for an overview of clickjacking defense measures beyond setting the XFO header.
The X-Frame-Options header is added on the server-side, not the client. This is because the header is used to control how the browser should render the page.
Whatever server is hosting your file would have to add this header.
Since you mention in the comments that IIS is your web server, yes, there is a way to set this on the web server itself.
Several of the other answers mention adding it to web.config, which is a fine option if this is an ASP.NET application, but there is another way that works for any web application being served from IIS, regardless of technology.
If you open the Internet Information Services (IIS) Manager
, and expand the node under Sites
in the navigation pane and highlight your site, under the IIS
features group in the Features View pane, there is a feature named HTTP Response Headers
. If you open this node, in the Actions
pane on the right, you see an action to add a header. Just add the header with the X-Frame-Options
name and whatever your desired value is, and it'll be added by IIS to every response served from that site.