使用postMessage指定window.frame
Specifying window.frame with postMessage
我使用postMessage将父页面css推送到每个iframe中的页面。问题是,在应用此代码之前,页面上可能已经有1个以上的iframe。因此,我如何将postMessage专门应用于每帧的id
,而不必手动输入window.frames[0]
和window.frames[1]
,其中[]
是根据页面调整的。
iframe
<iframe id="frame1" style="width: 100%; height: 420px;" src="../syndicatedPlayer.html#videoUrl=http://video.mp4?" frameborder="0"></iframe>
<iframe id="frame2" style="width: 100%; height: 420px;" src="../syndicatedPlayer.html#videoUrl=http://video.mp4?" frameborder="0"></iframe>
postMessage()
<script type="text/javascript">
var getFontFamily = function() {
var el = document.getElementsByTagName("h1")[0];
var cs = window.getComputedStyle(el, null);
return cs.fontFamily;
}
window.addEventListener('load', function(){
var data = getFontFamily("h1");
window.frames[0].postMessage(data, 'http://url.html');
window.frames[1].postMessage(data, 'http://url.html');
console.log('Message sent -->');
});
</script>
实际上是window===window.frames
,所以您只需使用window[0]即可获得帧。
也就是说,通过id获取iframe的一种方法是以下函数:
function getFrameById(id) {
for (var i=0;i<window.length;i++) {
if (window[i].frameElement.id===id) return window[i];
}
return null;
}
更新:我已经修复并完成了你的小提琴:http://jsfiddle.net/9qtcmbnn/4/
您可以指定要使用的iframe,方法是通过id选择它,然后从中发布想要的数据
你可以在下面使用它
<script>
function test1() {
document.getElementById('idMyIframe1').contentWindow.postMessage("your message here", "*");
}
function test2() {
document.getElementById('idMyIframe2').contentWindow.postMessage("your message here", "*");
}
</script>
<iframe id="idMyIframe1" onload="test1()" src="http://example.otherdomaintosenddatato.com"></iframe>
<iframe id="idMyIframe2" onload="test2()" src="http://example.otherdomaintosenddatato.com"></iframe>
相关文章:
- 正在寻找比$(document).ready慢的$(window).load的替代方案
- 直接下载文件,而不是从window.open(url)
- $window.ga在AngularJS事件中未定义
- 如何将PDF作为二进制文件传递到window.open()
- window.onload没有'无法在Android WebView中工作
- window.location替换并传递URL历史记录条目中的变量
- window.on.scroll事件未启动
- 可以<脚本类型=“;text/javascript”>window.location=“/"</
- 为什么window.open不打开一个以变量形式给出的链接
- window.location使用jquery mobile实现chrome跳转
- window.opener.document在ie中不起作用
- window.onpopstate不工作;当我导航回页面时,不会发生任何事情
- 未捕获的类型错误:topFrame.window.changeSelectedBarStyle不是函数,原因是什么
- 通过window.opener将弹出窗口中的值传递给父窗口
- $(document).height和$(window).heaght都返回相同的值-使用的是正确的doctype
- 如何在`window.open`之后执行回调
- 使用postMessage指定window.frame
- 移动野生动物园:frame.src vs window.location
- 当使用Javascript将URL分配给window.frame.location时,PHP页面不会加载
- “window.frame.openDialog"无法在Mac OS X中选择文件