Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

Firefox - Javascript - window.event not surviving pass to context.apply()

-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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...