How can I optimize the following postMessage functionality, so that it will attach the page to the correct iframe by id, and not by the location in the array window.frames[2]?
I'm using the following, which works:
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[2].postMessage(data, 'http://localhost:3000/syndicatedPlayer/syndicatedPlayer.html');
window.frames[3].postMessage(data, 'http://localhost:3000/syndicatedPlayer/syndicatedPlayer.html');
console.log('Message sent -->');
});
but would like to optimize this code, so that I don't have to find which iframe to use on the page(it should apply the post message to id="frame1" and id="frame2", not based on a manually entered frame.
The iframes that have the id's:
<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>
One thought was the following, but this is not working:
function getFrameById(id) {
for (var i = 0; i < window.length; i++) {
if (window[i].frameElement.id === id) {
console.log('found frame in index ' + i);
return window[i];
}
}
return null;
}
getFrameById('frame1').addEventListener("load", function (e) {
var data = getFontFamily("h1");
});
getFrameById('frame1').postMessage(data,
'http://jsfiddle.net/mattography/tmhfv2ft/1/show');
console.log('Message sent -->');
getFrameById('frame2').addEventListener("load", function (e) {
var data = getFontFamily("h1");
});
getFrameById('frame2').postMessage(data,
'http://jsfiddle.net/mattography/tmhfv2ft/1/show');
console.log('Message sent -->');
Example: jsfiddle