调用iframe子页面中的函数
parent.html
在父页面中,可以通过document.getElementById(id).contentWindow
访问子页面,有的浏览器支持document.frames[id]
,
还可以直接使用name="myIFrame"
中的myIFrame
作为变量名访问子页面。
<!-- parent.html -->
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
var dialog;
var dialogIframe;
function appendToDom(html){
try{
var tempDom = $(html).appendTo(document.body);
return tempDom;
}finally{
tempDom = null;
}
}
//根据id获取iframe的contentWindow
function getIFrame(id) {
return (document.getElementById(id) ? document.getElementById(id).contentWindow : null)
|| document.frames[id];
}
function say(){
alert("parent.html");
}
function callChild(){
// myFrame.window.say();
// myFrame.window.document.getElementById("button").value="调用结束";
console.log("content: ", dialog.content);
dialog.content.say();
}
$(document).ready(function() {
window.top.appendToDom("<div id='dialog_1' 'title='hello'></div>");
dialog = window.top.$("#dialog_1");
dialogIframe = window.top.$("<iframe id='iframe_1' src='child.html' ></iframe>").appendTo(dialog);
dialog.content = window.top.getIFrame("iframe_1");
});
</script>
</head>
<body>
<input id="button" type="button" value="调用child.html中的函数say()" onclick="callChild()"/>
<!-- <iframe name="myFrame" src="child.html" /> -->
</body>
</html>
child.html
子页面通过parent
访问父页面。
<!-- child.html -->
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function say(){
alert("child.html");
}
function callParent(){
parent.say();
parent.window.document.getElementById("button").value="调用结束";
}
</script>
</head>
<body>
<input id="button" type="button" value="调用parent.html中的say()函数" onclick="callParent()" />
</body>
</html>
问题
- Blocked a frame with origin “null” from accessing a cross-origin frame.
在chrome中测试出现,属于跨域请求错误,浏览器根据下面规则判断
://:/path/to/page.html
如果protocol,hostname,port不同,则认为是跨域,默认会阻止访问。
可以通过设置浏览器关闭判断。chrome
参考
Invoking JavaScript code in an iframe from the parent page
嵌套iframe页面中的JS调用