Skip to content

[BUG] 嵌套iframe会接受不到postMessage的消息 #1325

@xFeny

Description

@xFeny

问题描述

多层嵌套iframe,iframe会接受不到postMessage的消息,消息发送给了window.top

重现步骤

比如两层嵌套了iframe

<!doctype html>
<html lang="en">
  <body>
    <iframe src="a.html" width="820" height="595">
      <iframe src="https://player.bilibili.com/player.html?bvid=bv1aBXbBeEJ1&amp;autoplay=0" width="820" height="595"></iframe>
    </iframe>
  </body>
</html>

示例脚本

// ==UserScript==
// @name         iframe向父窗口传递信息
// @namespace    https://bbs.tampermonkey.net.cn/
// @version      0.1.0
// @description  iframe向父窗口传递信息,多层嵌套的话,只会发送给window.top
// @author       You
// @match        *://*/*
// ==/UserScript==

(function () {
    'use strict';

    const identify = 'send_data_to_parent_window'
    const inIFrame = () => window.top !== window.self;

    // 向父窗口传递信息
    const postMessage = () => window.parent.postMessage({ identify, href: location.href }, "*");

    document.addEventListener("play", () => postMessage(), true);

    window.addEventListener("message", ({ data }) => {
        if (!data?.identify) return;

        // a.html不打印信息,window.top有打印信息,Chrome ScriptCat v1.2.6+ 测试就没问题
        console.log('video 所在的 iframe:', data, '接收方:', location.href);
        if (inIFrame()) postMessage();
    })
})();

脚本猫版本

0.16.13

操作系统以及浏览器信息

Windows10 Firefox 149.0 (64 位)

补充信息 (选填)

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions