Languages
[Edit]
EN

JavaScript - escape webpage from iframe

7 points
Created by:
Welsh
902

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 iframe disables access to window.top object.
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>

 

See also

  1. JavaScript - detect if webpage is open in iframe

  2. HTTP - do not let to embed website in iframe

  3. apache2 - do not let to display website embedded in iframe

Alternative titles

  1. JavaScript - escape website from iframe
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join