Firefox - Javascript - window.event not surviving

2019-09-09 06:20发布

问题:

-This is the original question for posterity-

I'm having a bit of trouble with a new piece of code I wrote. I'm trying to find the iframe the window that sent a message lives in, assuming it's from an iframe at all. The relevant code:

var getContainingFrame = function(source){
    var frames = document.getElementsByTagName('iframe');
    for (var i = 0; i < frames.length; ++i) {
        if (frames[i].contentWindow === source) {
            return frames[i];
        }
    }
    return false;
}
var postMessageReceivedCallback = function(event){
    getContainingFrame(event.source);
}
window.addEventListener("message", postMessageReceivedCallback, false);

Works fine in Chrome/Safari, however Firefox matches the first frame every time. (iframe.contentWindow === window regardless of which window). I actually originally found how to do this from another post here, though they don't mention the problem with Firefox.

Each iframe has a different src.

Is there a different method for matching these? Have I done something obviously wrong?

No jQuery, please.

Thanks

Better Question:

My event was being passed through a function.apply(window, params) through the window object, expecting window.event available in the function it was applied to - this works in Chrome/Safari, thought not the case in FF. How do I get the event to be passed in FF?

回答1:

var someFunction = function(params){
    this.event.source //expect this to be the window the event originated in
    //... do something, like the iframe check
}
var postMessageReceivedCallback = function(event){
    //FF not keeping the event reference on the window that other browsers are,
    //so we add it ourselves from the event object passed by the message event.
    window.event = event;
    someFunction.apply(window, event.message);
}
window.addEventListener("message", postMessageReceivedCallback, false);