这是有问题的 JavaScript 代码
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);
Run Code Online (Sandbox Code Playgroud)
最后一行实际上抛出了这个错误消息:
Uncaught TypeError: Cannot read property 'postMessage' of undefined
Run Code Online (Sandbox Code Playgroud)
tmpIframe实际上是作为列表返回的。但即使我将最后一行更改为
tmpIframe[0].contentWindow.postMessage('do_something', data);
Run Code Online (Sandbox Code Playgroud)
我仍然收到相同的错误消息
为什么这不是有效的代码?我必须将 iframe 附加到 DOM 吗?
存在三个问题:
所以你可以使用 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);
Run Code Online (Sandbox Code Playgroud)
或者 jQuery:
$("<iframe></iframe>")
.load(function() {
console.log($(this).prop('contentWindow'));
$(this).remove();
})
.attr("src", url)
.appendTo('body');
Run Code Online (Sandbox Code Playgroud)