Home  >  Article  >  Web Front-end  >  How to Implement a Callback When an IFRAME Finishes Loading with Javascript?

How to Implement a Callback When an IFRAME Finishes Loading with Javascript?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-19 11:19:29470browse

How to Implement a Callback When an IFRAME Finishes Loading with Javascript?

Loading Iframe with Javascript Callback

To execute a callback when an IFRAME finishes loading, follow these steps:

Create the IFRAME and Load Handler

Create the IFRAME programmatically:

<code class="javascript">var iFrameObj = document.createElement('IFRAME');
iFrameObj.src = url;</code>

Add a load handler to the IFRAME:

<code class="javascript">$(iFrameObj).load(function() {
  // handle iframe load
});</code>

Access IFRAME Contents and Destroy It

Within the load handler, access the IFRAME's contents and destroy it:

<code class="javascript">function callback(iFrameObj) {
  // obtain iframe data
  var iframeData = $('body', iFrameObj.contentWindow.document).html();
  // destroy the iframe
  document.body.removeChild(iFrameObj);
}</code>

Additional Considerations

  • Ensure that if using timeouts for removal, set an appropriate delay to allow the IFRAME to load.
  • Avoid cross-site requests as their contents cannot be accessed.
  • Use jQuery for cross-browser compatibility and explicit load events.

Example

<code class="javascript">$('#myUniqueID').load(function() {
  if (typeof callback == 'function') {
    callback($('body', this.contentWindow.document).html());
  }
  setTimeout(function () {$('#frameId').remove();}, 50);
});</code>

The above is the detailed content of How to Implement a Callback When an IFRAME Finishes Loading with Javascript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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