简体   繁体   中英

contentWindow of a dynamically created iframe is undefined

This is the javascript code in question

var tmpIframe, url;
url = "http://local.custom.com:10000/simple.html";
tmpIframe = $("<iframe id='runner'></iframe>").attr('src', url);
tmpIframe.contentWindow.postMessage('do_something', data);

The last line actually throws this error message:

Uncaught TypeError: Cannot read property 'postMessage' of undefined

tmpIframe is actually returned as a list. But even if I changed the last line to

tmpIframe[0].contentWindow.postMessage('do_something', data);

I still get the same error message

Why this is not valid code? Do I have to append the iframe to DOM?

There are three problems:

  • You are mixing jQuery wrappers and DOM properties
  • Iframes must be appended to the DOM in order to be loaded
  • Iframes do not load immediately nor synchronously

So you can use vanilla-js:

var iframe = document.createElement('iframe');
iframe.onload = function() {
  console.log(iframe.contentWindow);
  document.body.removeChild(iframe);
};
iframe.src = url;
document.body.appendChild(iframe);

Or jQuery:

$("<iframe></iframe>")
.load(function() {
  console.log($(this).prop('contentWindow'));
  $(this).remove();
})
.attr("src", url)
.appendTo('body');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM