Home > Web Front-end > JS Tutorial > How Can I Dynamically Resize an iFrame Based on its Cross-Domain Content?

How Can I Dynamically Resize an iFrame Based on its Cross-Domain Content?

Patricia Arquette
Release: 2024-12-30 10:26:10
Original
1021 people have browsed it

How Can I Dynamically Resize an iFrame Based on its Cross-Domain Content?

Resizing an iFrame Based on Content: Navigating Cross-Domain Communication

Understanding the Cross-Domain Challenge

When displaying content from external domains within iFrames, the same-origin policy poses a challenge in dynamically resizing those iFrames to accommodate their content.

A Circumvention Strategy

One technique to bypass the cross-domain restriction involves exploiting a browser quirk that allows communication between pages in nested iFrame structures. In essence:

  • Parent page (www.foo.com/home.html) iframes child page (www.bar.com/framed.html).
  • Child page (www.bar.com/framed.html) iframes helper page (www.foo.com/helper.html).

This structure allows for communication between:

  • www.bar.com/framed.html and www.foo.com/helper.html (within the same iFrame)
  • www.foo.com/home.html and www.foo.com/helper.html (on the same domain)

Implementation

In www.foo.com/home.html:

<script>
  function resizeIframe(height) {
    document.getElementById("frame_name_here").height = parseInt(height) + 60;
  }
</script>
<iframe>
Copy after login

In www.bar.com/framed.html:

<body onload="iframeResizePipe()">
<iframe>
Copy after login

In www.foo.com/helper.html:

<body onload="parentIframeResize()">
<script>
  function parentIframeResize() {
    var height = getParam("height");
    parent.parent.resizeIframe(height);
  }

  function getParam(name) {
    var regex = new RegExp("[\?&]" + name + "=([^&]*)");
    var results = regex.exec(window.location.href);
    if (results == null) return "";
    else return results[1];
  }
</script>
Copy after login

This solution involves communication through a "helper" iframe (www.foo.com/helper.html) that resides on the same domain as the parent page and facilitates resizing requests between the child and parent iFrames.

The above is the detailed content of How Can I Dynamically Resize an iFrame Based on its Cross-Domain Content?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template