我使用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>