1. iframe使用postMessage进行通信

父页面:

// 父页面

useEffect(() => {
        previewAddEvent();
    }, [window]);


const showModalCb = (data) => {
        if (data.data) {
            try {
                const jsonParse = JSON.parse(data.data)
                if (jsonParse && jsonParse.postType === 'preview') {
                    console.log(jsonParse, typeof jsonParse);
                    setPopData(jsonParse); // 弹窗数据传参
                    setShow(true); // 是否显示弹窗
                }
            } catch (e) { }
        }
    }
    const previewAddEvent = () => {
        const domI: any = window;
        // 监听message事件
        try {
            if (domI.addEventListener) {
                domI.addEventListener('message', (data) => { showModalCb(data) }, false)
            } else {
                domI.attachEvent('onmessage', (data) => { showModalCb(data) })
            }
        } catch (err) {
            console.log(err)
        }
    }


标签
<iframe  className={styles.yIframe}  src={mySrc} id="previewIframe" frameBorder="0"/>

弹窗:
略....

子页面给父页面传参:

widow.parent.postMessage(JSON.stringify(item), '*')

2. 解决iframe标签预览文件,解决里面的全屏查看问题

问题背景:预览地址是后端给的地址,自带预览、放大缩小、旋转、全屏查看等功能,但全屏查看失败

代码:

<iframe
              src={viewFileUrl}
              style={{ width: '100%', height: '100%' }}
              title="预览"
            />

报错信息大概内容:

[Violation] Permissions policy violation: fullscreen is not allowed in this document. C @ app.js?v=xxx handleClickItem @ app.js?v=xxx click @ app.js?v=xxx qn @ app.js?v=xxx n @ app.js?v=xxx Nr.r._wrapper @ app.js?v=xxx app.js?v=xxx

Uncaught (in promise) TypeError: Disallowed by permissions policy at C (app.js?v=xxx) at a.handleClickItem (app.js?v=xxx) at click (app.js?v=xxx) at qn (app.js?v=xxx) at HTMLDivElement.n (app.js?v=xxx) at Nr.r._wrapper (app.js?v=xxx) 

解决办法: 添加allow="fullscreen"

<iframe
              src={viewFileUrl}
              style={{ width: '100%', height: '100%' }}
              title="预览"
              allow="fullscreen"
            />

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐