iframe内部对象调用与反向调用

本文通过一个具体实例展示了如何使用JavaScript在主页面与iframe子页面间进行双向通信,包括调用对方的函数及获取文本框内容。

iframe通常是页面内嵌的一个外部文件,我们可以通过Javascript访问iframe对象并操作iframe内嵌文件里面的DOM和Javascript对象。代码如下:

主页面文件index.html

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>index - iframe内部对象调用与反向调用[iTsai]</title>
</head>
<body>
<h3>页面最好在web容器(如:mongoose)中打开,chrome不支持iframe内函数离线调用</h3>
<iframe id="ifrm" name="ifrm" src="iframe.html" width="800" height="200"></iframe>
<br>
<br>
<input type="button" value="获取iframe文本框内容" onclick="getIframeTxt()">
<input type="button" value="执行iframe页面函数 i_foo()" onclick="call_i_foo()">
<input type="text" value="父页面文本框内容" id="p-txt">

<script type="text/javascript">
function p_foo(){
	alert('调用父页面 p_foo() 函数');
}
function getIframeTxt(){
	var iWindow = window.frames[0];//获取iframe页面window对象
	var iDocument = iWindow.document;////获取iframe页面document对象
	var txt = iDocument.getElementById("i-txt").value;
	alert(txt);
}
function call_i_foo(){
	window.frames[0].i_foo();
}
</script>
</body>
</html>

子页面文件iframe.html

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>iframe - iframe内部对象调用与反向调用[iTsai]</title>
</head>
<body>
<h2>iframe</h2>
<hr/>
<input type="button" value="获取父页面文本框内容" onClick="getParentTxt()"/>
<input type="button" value="执行父页面函数 p_foo()" onClick="call_p_foo()"/>
<input type="text" value="iframe页面文本框内容" id="i-txt">
<script type="text/javascript">
	function i_foo(){
		alert('调用iframe面 i_foo() 函数');
	}
	function getParentTxt(){
		var pWindow = window.parent;//获取父页面window对象
		var pDocument = pWindow.document;////获取父页面document对象
		var txt = pDocument.getElementById("p-txt").value;
		alert(txt);
	}
	function call_p_foo(){
		window.parent.p_foo();
	}
</script>
</body>
</html>

页面最好在web服务器(如:mongoose)中打开,chrome不支持离线iframe内函数调用,被认为是不安全的脚本访问。

iframe内部对象调用与反向调用

转载于:https://my.oschina.net/tsai/blog/78237

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值