window.open打开新窗口和调用iframe页面中方法

5,230 阅读1分钟

调用iframe中页面的方法

// 0.1html
<h1>11111111111111111</h1>
<script>
    window.test = function() {
        console.log('01---被你抓到了')
        return '我跑'
    }
 </script>
// 02.html
<h1>2222222222222222</h1>
    <button onclick="get()">获取方法</button>
    <iframe id="iframe" src="http://127.0.0.1:5500/01.html" width="600" height="600" frameborder="0"></iframe>
    <script>
        function get() {
            let data = document.getElementById('iframe').contentWindow.test()
            console.log('返回的数据---' + data)
        }
    </script>

window.open打开的页面调用父页面的方法

// 01.html
<button onclick="open1()">打开新页面</button>
<script>
    // 监听子页面发送消息
    window.addEventListener('message', (event) => {
      console.log(event.data) // 子页面发送过来的数据
      this.getDetail()
    })

    function open1() {
    	//这里是为了打开的窗口居中显示
        var top = (window.screen.height - 30 - 600) / 2
        var left = (window.screen.width - 10 - 1200) / 2
        window.open('http://127.0.0.1:5500/02.html', 'newwindow', 'height=600,width=1200,top=' + top + ',left=' + left + ',toolbar=no,menubar=no,scrollbars=no, resizable=no,location=no, status=no')
    }
 </script>
// 02.html
<button onclick="clickParent()">调用父页面的方法</button>
<script>
    function clickParent() {
        window.opener.postMessage('调用父页面的方法')
    }
</script>

新打开的页面