将函数从点击事件更改为窗口加载

Change function from click event to window load

本文关键字:窗口 加载 事件 函数      更新时间:2023-09-26

我正在尝试将postMessage从点击时向iframe发送消息更改为页面加载时发送消息。

在父页面上:

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

iframe页面包含以下内容以接收postMessage事件。

window.addEventListener('message', function(e){
        document.body.style.fontFamily = e.data;
        console.log('<---Message received');
    }, false);

如何在页面加载而不是点击时将css从父级加载到子级?

当前工作示例:jsfiddle

从此更改代码:

window.addEventListener('click', function(){

到此:

window.addEventListener('load', function(){

更新的小提琴:http://jsfiddle.net/nzjfn6u4/2/