子级(登录)

 <div class="login">
        <form  >
            <div class="form-item">
                <label for="username">用户名:</label>
                <input type="text" name="username" id="username" placeholder="请输入用户名">
            </div>
            <div class="form-item">
                <label for="password">密码:</label>
                <input type="text" name="password" id="password" placeholder="请输入密码">
            </div>
            <div class="form-item">
                <input type="submit" value="登录">
            </div>
        </form>
    </div>
<script>
        // 监听父级传递过来的数据
        window.addEventListener('message', function(e) {
            console.log('父widonw传递过来的数据:',JSON.parse(e.data));
        })
     
        const form = document.querySelector('form'); 
        form.addEventListener('submit', function(e) { 
            e.preventDefault();
            // 获取用户名
            const username = document.querySelector('#username').value; 
            // 获取密码
            const password = document.querySelector('#password').value; 
            window.parent.postMessage({username, password}, '*');
        }) 
 </script>

父级

<body>
    <iframe src="./login.html" id="iframeByLogin"></iframe>

    <script>
        // 监听子级传递过来的数据
        window.addEventListener('message', function(e) {
            console.log('子(登录iframe)传递过来的数据:',e.data );
        })


        const _iframeLogin = document.querySelector('#iframeByLogin');
        _iframeLogin.onload = function() {
            let param = {
                username: 'admin',
                password: '123456'
            }
            _iframeLogin.contentWindow.postMessage(JSON.stringify(param), '*');
        } 
    </script>
    
</body>

简单即可
6 声望2 粉丝