js 的 iframe 父子页面通讯的简单方法

一、获取 子页面 的 window 对象 javascript

在父页面中,存在以下两个对象html

window.framesjava

document.iframeElement.contentWindow函数

能够获取到 子页面 window 对象this

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

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

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

既然拿到了 window 对象,那函数和DOM就到手了。code

二、子 iframe 获取 父页面htm

window.parent 对象对象

window.top对象ip

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

window.parent 即为当前页面的上一级页面的 window 对象,若是当前页面已经是 顶层 页面,则 window.parent 就是本身。get

三、小实例

<!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>
相关文章
相关标签/搜索