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.
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/