You have, you can do as I explained in JavaScript - Difference between this
and self
, then inside the page that can possibly be called inside the iframe add this:
if (window.top !== window.self) {
alert('Esta página foi provavelmente chamada dentro de um iframe');
} else {
alert('Esta página foi aberta diretamente na aba/janela');
}
What each property does:
You may also want to check if the domain is the same as your domain then the function does not occur, for example:
if (window.top.location.host !== window.location.host) {
alert('Sua página foi embarcada por um dominio diferente');
} else if (window.top !== window.self) {
alert('sua página foi provavelmente embarcada por uma página do mesmo dominio');
} else {
alert('Esta página foi aberta diretamente na aba/janela');
}
Redirecting
If you want to redirect to your own site you can use .location = ...
or .location.replace(...)
, the difference between them is that location.replace
will replace the current page, making the page that had iframe not and forward , which may be more interesting, eg
if (window.top !== window.self) {
alert('Este site não permite enquadramentos (frame), você esta sendo redirecionado'); //Mensagem opicional
window.top.location.replace(window.self.location.href);
}
X-Frame-Options
However, one interesting thing you can use to prevent embed (if that's what you want) is to use the header X-Frame-Options
, which can be added via server-side or even via .htaccess, web.config, etc. There are 3 possible values:
-
X-Frame-Options: DENY
Prevents embed using frame or iframe from any site, even the site itself
-
X-Frame-Options: SAMEORIGIN
Prevent site with domains other than your own from loading your page (s), but if it is the same domain then you can
-
X-Frame-Options: ALLOW-FROM https://sitepermitido.com/
Allows a specific site to upload your page (s).
Examples with SAMEORIGIN
:
-
.htaccess :
Header add X-Frame-Options "SAMEORIGIN"
-
web.config ( ...
is to indicate that you can add more settings):
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="X-Frame-Options" value="SAMEORIGIN" />
...
</customHeaders>
</httpProtocol>
...
</system.webServer>
</configuration>
-
nginx.conf :
location pasta_especifica {
add_header X-Frame-Options SAMEORIGIN;
}
-
PHP :
<?php
header('X-Frame-Options: SAMEORIGIN');
-
asp.net (in c # , I think it's not much different if written in vb.net)
Response.AppendHeader("X-Frame-Options", "SAMEORIGIN");