JavaScript - escape webpage from iframe
In this short article, we would like to show how to detect if website is open in iframe and navigate out from the iframe using JavaScript. It means, presented solution do not let to display website in the iframe.
Warning: the below solution will be not working if
iframedisables access towindow.topobject.
Solution: check this article for better solution.
Hint: the below example result is open in
iframe, so running it we will be redirected to https://dirask.com.
Quick solution:
// ONLINE-RUNNER:browser;
<!DOCTYPE html>
<html>
<body>
<script>
if (window.top !== window) {
window.top.location.href = 'https://dirask.com';
}
</script>
</body>
</html>
Hint: add the above source code to website template to make it working on each webpage - it is good to put it at the begining of your website to make redirection as soon as it possible.
Alternative solutions
location.assign() method example
It is the same solution like in location.href property case (like in quick solution presented).
// ONLINE-RUNNER:browser;
<!DOCTYPE html>
<html>
<body>
<script>
if (window.top !== window) {
window.top.location.assign('https://dirask.com');
}
</script>
</body>
</html>
location.replace() method example
This approach removes from navigation history, website that embedded other webite in iframe.
// ONLINE-RUNNER:browser;
<!DOCTYPE html>
<html>
<body>
<script>
if (window.top !== window) {
window.top.location.replace('https://dirask.com');
}
</script>
</body>
</html>
Automatic solution
By using location.origin it is not necessary to hardcode redication path.
// ONLINE-RUNNER:browser;
<!DOCTYPE html>
<html>
<body>
<script>
if (window.top !== window) {
window.top.location.href = location.origin;
/*
or:
window.top.location.assign(location.origin);
or:
window.top.location.replace(location.origin);
*/
}
</script>
</body>
</html>