I am trying to change postMessage
from sending a message to an iframe on click to sending it on page load.
On the parent page:
var el = document.getElementById('button');
var getFontFamily = function(){
for(var i = 0; i < document.styleSheets.length; i++){
for(var j = 0; j < document.styleSheets[i].rules.length; j++){
if(document.styleSheets[i].rules[j].style.fontFamily){
return document.styleSheets[i].rules[j].style.fontFamily;
}
}
}
return 'not-found';
};
window.addEventListener('click', function(){
var data = getFontFamily();
window.frames[0].postMessage(data, 'http://localhost:3000');
console.log('Message sent -->');
});
The iframe page has the following to receive the postMessage
event.
window.addEventListener('message', function(e){
document.body.style.fontFamily = e.data;
console.log('<---Message received');
}, false);
How can I change this to load the css from the parent to the child on page load and not on click?
Current working example: jsfiddle
Change your code from this:
window.addEventListener('click', function(){
to this:
window.addEventListener('load', function(){
Updated fiddle: http://jsfiddle.net/nzjfn6u4/2/