我在index页面嵌套一个iframe,引入iframe.html,iframe上有一个方法,叫‘say’,在iframe页面将其赋给父window。(两个页面同域)
Q:
以下是两个页面的源码:
index.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<iframe src="./iframe.html" frameborder="0"></iframe>
<button onclick="deleteDOM()">delete</button>
<button onclick="say()">say</button>
<button onclick="rebornIframe()">rebornMap</button>
</body>
<script>
function deleteDOM() {
document.body.removeChild(document.getElementsByTagName('iframe')[0]);
}
function say(){
if (window.sayHello) {
sayHello()
}
}
function rebornIframe(){
var createNode = document.createElement('iframe');
var createAttr = document.createAttribute('src');
createAttr.value = "iframe.html";
createNode.setAttributeNode(createAttr);
document.body.appendChild(createNode);
}
</script>
</html>
iframe.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<title></title>
</head>
<body>
<p>this is a iframe</p>
</body>
</html>
<script type="text/javascript">
var sayHello = function(){
console.info('hello')
};
window.parent.sayHello = sayHello;
var obj = {
a:1
};
window.parent.obj = obj;
var Person = function(name){
this.name = name;
};
var student = new Person('xiaoming');
window.parent.student = student;
</script>
走同样的路,发现不同的人生