iframe嵌套页面传值

前言:

        最近负责的项目大部分都是在别人的网站中通过iframe标签嵌套我方页面,而且项目没有使用近年来流行的框架,所以在本文中的代码只是基于js进行编写。

一、父向子传值

        方法一:通过src拼接上需要传递的参数

        父页面

<body>
    <div>父级页面</div>
    <iframe src="2.html" id="frame1" frameborder="0"></iframe>
    <script>
        // 方法一:通过src向子元素传递参数
        let url = document.getElementById('frame1').src + '?name=LeeYuFan&sex=女' //拼接上需要传递的参数
        document.getElementById('frame1').src = url
    </script>
</body>

        子页面

<body>
    <div>子页面--2.html页面</div>
    <script>
        window.onload = function(){
            let name = getUrlParam('name')
            let sex =  decodeURIComponent(getUrlParam('sex')) //解码
            console.log(name,sex)
        }
        function getUrlParam(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); // 构造一个含有目标参数的正则表达式对象
            var r = window.location.search.substr(1).match(reg); // 匹配目标参数
            if (r != null)
                return r[2];
            return null; // 返回参数值
        }
    </script>
</body>

        方法二:通过window对象的postMessage()方法

数据发送方(父页面)

<body>
    <div>父级页面</div>
    <iframe src="2.html" id="frame1" frameborder="0"></iframe>
    <script>
        window.onload = function(){
            // 方法二:通过postMessage()方法
            let send = document.getElementById('frame1').contentWindow;
            send.postMessage("被传递的数据",'*')
        }
    </script>
</body>

数据接收方(子页面)

<body>
    <div>子页面--2.html页面</div>
    <script>
       window.onload = function(){
            window.addEventListener('message',function(e){
                console.log(e.data)
            })
       }
    </script>
</body>

注:

1、postMessage(参数1,参数2,[参数3])方法有三个参数,参数1代表将要发送的数据;参数2代表指定哪些窗口能结合搜到消息事件,其值可以是*或一个URL,(‘*’代表无限制);参数3可选,是一串和 message 同时传递的 Transferable 对象。这些对象的所有权将被转移给消息的接收方,而发送一方将不再保有所有权。

2、接收方的回调函数中包含三个常用的数据:

        e.source --消息源,消息发送的窗口/iframe

        e.origin -- 消息源的URI,用来验证数据源

        e.data -- 发送过来的数据

二、子向父传值

方法一:子页面把要传递给父元素的参数定义为全局变量,然后父页面直接获取

子页面定义变量

<body>
    <script>
        var name = 'LeeYuFan'
    </script>
</body>

父页面读取变量

<body>
    <div>父级页面</div>
    <iframe src="3.html" id="frame2" frameborder="0"></iframe>
    <script>
        window.onload = function(){
            console.log(document.getElementById('frame2').contentWindow.name)
        }
    </script>
</body>

方法二:使用postMessage()方法

子页面

<body>
    <div>子页面--2.html页面</div>
    <script>
      window.parent.postMessage('123','*')
    </script>
</body>

父页面

<body>
    <div>父级页面</div>
    <iframe src="2.html" id="frame1" frameborder="0"></iframe>
    <script>
        window.onload = function(){
            window.addEventListener('message',function(e){
                console.log(e.data)
            })
        }
    </script>
</body>

猜你喜欢

转载自blog.csdn.net/m0_73334325/article/details/128522037