Message Event Handler Exist or not in window objec

2019-08-20 18:36发布

i have a page in html contains iframe.if message comes from iframe i have to handle it.but how to check if message event handler exist or not my code is

$(window).on('message',function(e){
console.log(e.originalEvent.data);
}); 

when button is clicked this code set message event handler.but when again clicked again message handler get added .Is there any method to know if in window object is message event handler present or not.Please guideline.i can't use global variable in my case.if its possible to get event handler from window object then please explain the method.

1条回答
我命由我不由天
2楼-- · 2019-08-20 19:34

Try

$(function () {
    $("body").text("click");
    // `message` `handler`
    window.msgHandler = function (e) {
        if (e.origin === "http://fiddle.jshell.net") {
            console.log(e, e.data);
        };
    };
    window.addEventListener('message', msgHandler, false);
    var iframe = $("<iframe>", {
            "width": "150px",
            "height": "150px",
            "target": "_top"
    });
    $(iframe).one("load", function (e) {
        var _data = $(e.target)[0].nodeName + " loaded at " + e.timeStamp;
        window.postMessage(_data, "http://fiddle.jshell.net");

        $(e.target)
            .contents()
            .find("html")
            .html("<html><body><div>" 
                  + _data 
                  + "</div><br /></body></html>");
        return false
    });
    var loadFrame = function (e) {
        // if in window object is message event handler present or not
        console.log("msgHandler" in window
                    ? [ window.msgHandler
                      , window.msgHandler.toString()
                      , typeof window.msgHandler ] 
                    : false);
        $(e.target)
            .text("")
            .append($(iframe))
    };

    $(window).one("click", loadFrame);
});

jsfiddle http://jsfiddle.net/guest271314/9xC27/

查看更多
登录 后发表回答