A simple method of js iframe parent-child page communication

1. Get the window object of the child page 

In the parent page, there are the following two objects

window.frames

document.iframeElement.contentWindow

You can get the child page window object

// iframe id
document.getElementById('menuIframe').contentWindow

// iframe name
window.frames['menuIframe'].window

// iframe index 当前窗体的第几个 iframe
window.frames[1].window

Now that you have the window object, the functions and the DOM are in your hands.

2. The child iframe gets the parent page

window.parent object

window.top object

// 判断当前页面是否是 iframe 或 顶级页面
window.parent == window
window.top == window

window.parent is the window object of the previous page of the current page. If the current page is already the top-level page, then window.parent is itself.

3. Small example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <iframe src="/sub.html" name="iframeContainer" id="iframeContainer"></iframe>
    <script type="text/javascript">
        function parentHello() {
            alert("this is parent hello function!");
        }
        window.frames['iframeContainer'].subHello();
    </script>
</body>
</html>

<!-- sub.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <script type="text/javascript">
        function subHello() {
            alert("this is sub hello function!");
        }

        window.parent.parentHello();
    </script>
</body>
</html>

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324981307&siteId=291194637