Anthony Kong
Anthony Kong

Reputation: 40824

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?

Upvotes: 1

Views: 3972

Answers (1)

Oriol
Oriol

Reputation: 288620

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');

Upvotes: 5

Related Questions