Yes, 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 every property does:
window.self
returns the current window object
window.top
returns the window object above all, for example if a page has an iframe called #frame1
and this iframe has another iframe called #frame2
, then in #frame2
use window.top
it will return the page object that embarked the #frame1
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 website you can use .location = ...
or .location.replace(...)
, the difference between the two is that location.replace
will replace the current page, causing the page that had iframe nay is available on back and forward, what can be more interesting, example:
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 an interesting thing you can use to prevent the embed (if that’s what you want) is to use the header X-Frame-Options
, which can be added via language 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
Prevents sites with domains other than your own from shipping your (s) page(s), but if it is the same domain then you can board
X-Frame-Options: ALLOW-FROM https://sitepermitido.com/
Allows a specific site to ship your page(s)).
Examples with SAMEORIGIN
:
.htaccess:
Header add X-Frame-Options "SAMEORIGIN"
web config. (the ...
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 don’t think it’s much different if written in Vb.net)
Response.AppendHeader("X-Frame-Options", "SAMEORIGIN");
All that was missing was a little example :)
– Wallace Maxters