Home > Web Front-end > JS Tutorial > body text

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

Patricia Arquette
Release: 2024-10-19 11:19:29
Original
470 people have browsed it

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>
Copy after login

Add a load handler to the IFRAME:

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

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>
Copy after login

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>
Copy after login

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!

source:php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!