未定义动态创建的iframe的contentWindow [英] contentWindow of a dynamically created iframe is undefined

查看:2374
本文介绍了未定义动态创建的iframe的contentWindow的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是有问题的javascript代码

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 实际上是作为列表返回的。但即使我将最后一行更改为

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

为什么这不是有效的代码?我是否必须将iframe附加到DOM?

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

推荐答案

有三个问题:


  • 您正在混合使用jQuery包装器和DOM属性

  • 必须将iframe附加到DOM才能加载

  • iframe不立即加载或同步加载

所以你可以使用vanilla-js:

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

或jQuery:

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

这篇关于未定义动态创建的iframe的contentWindow的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆