postMessage Source IFrame

前端 未结 6 1918
执念已碎
执念已碎 2020-12-13 15:21

I\'m working on a website with cross-domain iframes that are resized to the correct height using postMessage. The only problem I\'m having is identifying which iframe has wh

6条回答
  •  鱼传尺愫
    2020-12-13 15:42

    If the source iframe is nested in more than one parent iframe, then you will need to recurse over the window.frames property of each iframe and compare it against the messageEvent#source property.

    For example, if the message is generated by iframe#level3 of this Dom.

    
    
    

    You should be able to find the index of the ancestor iframe in the current window using.

    FindMe = event.source
    FrameIndex = find(window)
    frames[FrameIndex].frameElement ==     getElByTagName(iframe)[FrameIndex] 
    
    function find(target){
        for (i=0; I< target.frames.length; i ++)
           if(target.frames[i] == FindMe ||   find(target.frames[i]))
               return i
        return false 
    }
    

    Its important to note that

    The Window.frames property is not restricted by cross domain policy

    This technique will work regardless of how deeply nested the source iframe happens to be

    window.frames is a collection of window objects not iframe elements.

    access to the propetties s of the memebers of the window.frames collection is resttictred by Same Origin (I.e you may not be able to access the frameElement or location properties of window.frames[i]

提交回复
热议问题