实现iframe内嵌页面与父页面通讯

详细介绍地址:https://developer.mozilla.org/zh-CN/docs/Web/API/Window/postMessage

iframe内嵌页面发送数据


<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
head>
<body>
    <div class="container">
        <span>
            <p>页面将在<p class="timer">3p>秒后自动关闭p>
        span>
    div>
    <script>
        let count = 3;
        setInterval(() => {
          count--;
          document.getElementsByClassName('timer')[0].innerHTML = count;
          if (count === 0) {
          //向父页面发送数据,参数包括message(发送数据内容)和targetOrigin(其值可以是字符串"*"(表示无限制)或者一个URL)
            window.parent.postMessage('error', '*');
          }
        }, 1000);
    script>
body>

html>

父页面监听

<script>
export default {
  name: 'FilePreview',
  data() {
    return {
    
    };
  },
  mounted() {
    /**
     * 监听iframe内嵌页面的message通讯
     */
    window.addEventListener('message', (e) => {
      const { data } = e;
      if (data === 'error') {
      //此处写需要执行的方法
      console.log('dddd');
      }
    });
  },
  render() {
    return (
        <div class='file-preview-wrapper' >
            <iframe 
              title="文件预览"
              width="100%"
              height="100%"
              frameborder="0" scrolling="auto"
              src='https://www.baidu.com/'>
            </iframe>
        </div>
      ) 
  },
};
</script>

<style lang="scss" >
@import "./index.scss";
</style>

你可能感兴趣的:(vue,jsx渲染,iframe)