Hoooray! In former times, you had to say:
The server can't know if the client loaded the page in an iframe
which makes a lot of sense in a traditional Client-Server modal. But well, the browser decides, if it doesn't tell the server about it. And new browsers are very friendly and let us know:
The browser tells the server in which context the request is created with Sec-Fetch-Site header!
This is great news as it was a pain before to allow the server special handling of content loaded in special context.
A typical case is to hide certain regions of a page if the content was loaded in an iframe (for example, hide the menu bar and only show the page content in iframe modals)!
Other cases might be to prevent responses to requests from certain contexts at all!
Traditional alternatives to this were for example providing a GET parameter like ?iframe=1
which was also a pain as you had to ensure the parameter is kept for all other requests starting from that context. So it's really, really helpful to have this clever solution now.
The new header is documented here and not only usable for iframe, but also for many other contexts like audio, embed, script, object, and others.
For details, see the documentation on
https://symfony.com/doc/current/components/http_foundation.html#accessi…
or
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Sec-Fetch-Dest
Browser support:
You have to be a bit careful with browser support as the functionality is quite new (as of 2021-07): https://caniuse.com/mdn-http_headers_sec-fetch-dest
Especially the fact that Safari doesn't support the header, might be relevant in many cases.
How to use / implementation:
Implementation is simple, if you have no conflicts with older browsers:
PHP example:
if ($_SERVER['HTTP_SEC_FETCH_DEST'] == 'iframe') {
// Hide certain parts of the page
}
Symfony example:
$request = Request::createFromGlobals();
if ($request->server->get('HTTP_SEC_FETCH_DEST') == 'iframe') {
// Hide certain parts of the page
}
Twig example:
{% if app.request.server.get('HTTP_SEC_FETCH_DEST') == 'iframe' %}
{# Hide certain parts of the page#}
{% endif %}
If you're interested in the discussion about the new header, you may like to read https://github.com/w3c/webappsec-fetch-metadata/issues/16