Home  >  Article  >  Web Front-end  >  How to Handle IFrame Loading Events in Javascript without Accessing Content?

How to Handle IFrame Loading Events in Javascript without Accessing Content?

Linda Hamilton
Linda HamiltonOriginal
2024-10-19 10:07:30913browse

How to Handle IFrame Loading Events in Javascript without Accessing Content?

IFrame Loading Event Handling in Javascript

In Javascript, executing a callback upon completion of IFRAME loading is possible, even if the IFRAME content is inaccessible. Here's how to achieve this:

Method:

  1. Create the IFRAME programmatically and append it to the DOM.
  2. Use the jQuery .load() event handler to detect IFRAME load completion.
  3. Employ a timeout (e.g., 50 milliseconds) within the callback to delay IFRAME removal, ensuring data retrieval.

Example:

<code class="js">$('#myUniqueID').load(function () {
    if (typeof callback === 'function') {
        // Retrieve the IFRAME body content and pass it to the callback
        callback($('body', this.contentWindow.document).html());
        // Remove the IFRAME after a short delay to allow content retrieval
        setTimeout(function () { $('#myUniqueID').remove(); }, 50);
    }
});</code>

Note: If the IFRAME content is served from a different domain, retrieving its body will not be possible due to cross-origin resource sharing (CORS) restrictions.

The above is the detailed content of How to Handle IFrame Loading Events in Javascript without Accessing Content?. 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