Iframe DOMContentLoaded Does Not Fire

Asked 1 months ago, Updated 1 months ago, 1 views

■ Event
Create iframe dynamically and
Add "DOMContentLoaded" to addEventListener, but
No event occurs when iframe src destination DOM read is complete.

■ Coding

var parent_obj= document.getElementById("top");
varobj= document.createElement('iframe');

if(obj.addEventListener){
    obj.addEventListener("DOMContentLoaded", xxx); // ★ This Does Not Fire
    // obj.addEventListener("load", xxx); // ☆ Slow
} else if(obj.attachEvent) {
    obj.attachEvent("onload", xxx);
} else {
    obj.onload=xxx;
}

parent_obj.appendChild(obj);
obj.src = "URL";

function xxx(e){
    alert("fire"; ★ This does not ignite
}

■What you want to do
AddEventListener("load", xxx) is slow because the event occurs after loading the image.
I want to call an event right after I get the iframe source back.

■Question
Why doesn't DOMContentLoad fire?
Is the coding bad?

Or is createElement('iframe') not compatible with DOMContentLoaded events?
In that case, is there an alternative to what you want to do above?

javascript html

2022-09-30 14:21

2 Answers

First, DOMContentLoaded is an event that fires on Window and cannot be used for iframe elements.

For cross-origin, you must manipulate the HTTP header or script on the iframe side page.
If you can't do that, you can't use the following methods… or rather, it's probably impossible.

Method 1. Aligning Domains of Both Documents

If the parent and iframe upper domains are in common, the following script simply aligns the page document domain with the upper domains.

 document.domain="your-domain.com";

Note: Same Origin Policy #Change Origin - MDN

If you do not have a common parent domain, use the following method 2 or 3:

Method 2. Allow iframe to operate from parent origin

If you can add an HTTP header on the iframe side, print the following header from the server side:

Access-Control-Allow-Origin: http://your-parent-page.com

How to Use 3.postMessage

I can manage with window.postMessage which is a little troublesome but can communicate with cross-domain.
See window.postMessage-MDN for more information on behavior and other details.

Parent page:

window.addEventListener("message", messageCallback, false);

function messageCallback(event){
  if(event.origin!=="http://your-iframe-page.com")return;
  if(event.data==="iframe loaded!") {
    /* Load Complete*/
    alert("Fire";
  }
}

iframe page:

window.addEventListener("DOMContentLoaded", loadedCallback, false);

function loadedCallback(event){
  window.parent.postMessage("iframe loaded!", "http://your-parent-page.com");
}


2022-09-30 14:21

HTMLIFrameElement has properties called contentWindow and contentDocument, so you might want to pick up that event.

obj.contentDocument.addEventListener("DOMContentLoaded", xxx);


2022-09-30 14:21

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.