2016-12-15 65 views
0

我有一個影子DOM的iFrame:的postMessage到iFrame的陰影DOM有event.source集最晚將event.target鉻

<iframe id="output-frame" src="http://localhost:8080/external/output.html" data-src="http://localhost:8080/external/output.html" style="height: 570px; width: 322px;"> 
    #document 
     <html>...</html> 
</iframe> 

我發個帖子消息吧:

postFrameOrigin: function postFrameOrigin() { 
    var match = /^.*:\/\/[^\/]*/.exec(this.$el.find("#output-frame").attr("data-src")); 

    return match ? match[0] : window.location.protocol + "//" + window.location.host; 
}, 

postFrame: function postFrame(data) { 
    // Send the data to the frame using postMessage 
    this.$el.find("#output-frame")[0].contentWindow.postMessage(JSON.stringify(data), this.postFrameOrigin()); 
    // Here `postMessage` is called ... 
}, 

我接受它的影子DOM:

bind: function bind() { 
    // Handle messages coming in from the parent frame 
    window.addEventListener("message", this.handleMessage.bind(this), false); 
    // ... here `message` is received ... 
}, 

handleMessage: function handleMessage(event) { 
    var data; 

    this.frameSource = event.source; // event.source contains target (falsly?) 
    this.frameOrigin = event.origin; 

(...) 

在Firefox和Chrome瀏覽器,直到版本52,我收到源對象正確在event.source。從版本53開始,它包含目標對象,與event.targetevent.srcElement中的相同。 (還有最近的歌劇,因爲他們使用Blink)。閃爍切換到該版本的影子dom V1。它看起來像有一個連接。

這是一個錯誤?如果不是,那麼我如何才能訪問源對象呢?

回答

1

在我的版本的Chrome(V57)和Opera(V41)的他們仍然是不同的:

console.assert(event.source !== event.target)不會引發任何異常。

另外,如果我給不同的名稱到主窗口和框架窗口:

var window.name = 'container' 
... 
<iframe name="frame" ...> 

...我可以在handleMessage()回調看着他們:

console.log(event.source.name) // = container 
console.log(event.target.name) // = frame