Reputation: 40824
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
Reputation: 288620
There are three problems:
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