首页

测试获取iframe加载后内容或调用其内部方法示例(兼容主流浏览器)

标签:框架,js,javascript,frames,前端,页面嵌套,父窗口,子窗体,contentWindow,兼容,about:blank,代码示例,案例     发布时间:2016-08-17   

一、示例简介

该代码示例通过 javascript代码主要调用iframe页面内部方法和获取节点内容,必须等iframe的src地址对应的页面都加载完成后,才能开始调用测试,否则页面获取的url为“about:blank”,获取的内容方法会报undefined,通过jquery获取iframe节点内容参考更多页

二、代码内容

1. 主测试页面代码如下,分别调用iframe的方法和内容

<html>@b@<head> @b@<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> @b@ <script>  @b@ function getIframeWin(id){  @b@     var win;@b@     if (document.all){ // IE@b@        win = document.frames[id];@b@     }else{ // 标准@b@        win = document.getElementById(id).contentWindow;@b@     }  @b@    return win;@b@}  @b@ function invokeMethod(){@b@    getIframeWin('frame1').test();@b@ } @b@ function invokeText(){@b@    var cons=getIframeWin('frame1').document.getElementById("ibody").innerHTML;@b@    alert(cons);@b@ } @b@ </script> @b@</head>@b@<body>   @b@<body> @b@<button onclick="invokeMethod();">调用方法 </button>@b@<button onclick="invokeText();">调用内容 </button>@b@<iframe id="frame1" src="iframe.html" ></iframe> @b@</body></html>

2. iframe页面内容如下

<html>@b@<head> @b@<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> @b@ <script>@b@ function test(){@b@    alert('iframe内容测试方法test调用ok了!!!');@b@ }@b@ </script> @b@</head>@b@<body> @b@<body> @b@<div id="ibody">我是iframe页面 ,含有 test()的js方法</div>@b@</body></html>

3. 效果如下