"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Implement a Callback When an IFRAME Finishes Loading with Javascript?

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

Published on 2024-11-07
Browse:438

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:

var iFrameObj = document.createElement('IFRAME');
iFrameObj.src = url;

Add a load handler to the IFRAME:

$(iFrameObj).load(function() {
  // handle iframe load
});

Access IFRAME Contents and Destroy It

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

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

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

$('#myUniqueID').load(function() {
  if (typeof callback == 'function') {
    callback($('body', this.contentWindow.document).html());
  }
  setTimeout(function () {$('#frameId').remove();}, 50);
});
Release Statement This article is reprinted at: 1729302797 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3