关于父页面访问iframe中元素和js的那点事

page1.html

<html>
    <body>
        <input type="button" onclick="getValue()" value="获取外部网页" />&nbsp;
        <input type="button" onclick="getValue2()" value="获取内部网页" />&nbsp;
        <input type="button" onclick="getValue3()" value="获取内部http网页" />&nbsp;
        <input type="button" onclick="getValue4()" value="调用内部页面的js方法" />&nbsp;
        <input type="button" onclick="getValue5()" value="获取相同机器的别的项目的页面" />&nbsp;
        <hr/>
        <iframe name="frame1" id="frame1" src="http://www.baidu.com" height="300"></iframe>
        <iframe name="frame2" id="frame2" src="page2.html" height="300"></iframe>
        <iframe name="frame3" id="frame3" src="http://localhost:8080/cc360/page2.html" height="300"></iframe>
        <iframe name="frame4" id="frame4" src="http://localhost:8080/storess/page2.html" height="300"></iframe>
    </body>
    <script>
        //获取baidu的搜索文本框的值,失败,禁止跨域访问
        function getValue(){
            alert(document.frame1.document.getElementById("kw").value);
        }
        //获取相同页面下的page2页面中的input的值,成功
        function getValue2(){
            alert(document.frame2.document.getElementById("ins").value);
        }
        //获取相同域下的页面中的input的值,成功
        function getValue3(){
            alert(document.frame3.document.getElementById("ins").value);
        }
        //调用相同域下的页面中JS方法,成功
        function getValue4(){
            document.frame3.test();
        }
        //调用相同机器的别的项目下的页面,成功
        function getValue5(){
            alert(document.frame4.document.getElementById("ins").value);
        }
    </script>
</html>

page2.html

<html>
    <body>
        <input type="text" name="ins" id="ins" value="11" />
    </body>
    <script>
        function test(){
            alert("js");
        }
    </script>
</html>

测试时的访问路径:http://localhost:8080/test/page1.html

测试的结果表示:只要http://ip:端口/    相同就可以访问子页面中的任何元素

原文地址:https://www.cnblogs.com/yangzhilong/p/2998035.html