带有阴影dom的postMessage到iFrame,在最新的Chrome中将event.source设置为event.target

时间:2016-12-15 10:57:35

标签: google-chrome events iframe postmessage shadow-dom

我有一个带阴影dom的iFrame:

<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相同。 (也是最近的Operas,因为他们使用Blink)。 Blink切换到此版本的影子dom V1。看起来有连接。

这是一个错误吗?如果没有,那我怎么才能访问源对象呢?

1 个答案:

答案 0 :(得分: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
相关问题