iframe和页面处在不同域下,iframe操作页面的属性与方法
问题来源:
当iframe和父页面处在不同域下,会因为跨域造成限制,拿不到父页面的大多数属性与方法
解决方案:
通过代理页面解决跨域问题
1、在父页面中设置一个sessionStorage
http://localhost:3333/public/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
父页面
<iframe id="iframe" name="iframe" src="http://localhost:3334/public2/index3.html" frameborder="0"></iframe>
</body>
<script>
(function setSession(){
window.sessionStorage.setItem('str','123')
})()
function getSession(){
console.log(window.sessionStorage.getItem('str'))
}
</script>
</html>
2、然后在父页面同一域下新建一个agent.html
页面
http://localhost:3333/public/agent.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
代理页面
</body>
<script>
window.onload = function(){
window.top.getSession()
}
</script>
</html>
3、最后在iframe页面中创建一个看不见的iframe来加载这个代理页面
http://localhost:3334/public/index3.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div>
iframe页面
</div>
</body>
<script>
(function(){
if(!document.getElementById('crossFrame')){
var iframe = document.createElement('iframe')
iframe.setAttribute('id', 'crossFrame')
iframe.setAttribute('src', 'http://localhost:3333/public/agent.html')
iframe.setAttribute('style', 'position: absolute; top: -9999px; left: -9999px;')
document.body.appendChild(iframe)
} else {
document.querySelector('#crossFrame').src = 'http://localhost:3333/public/agent.html'
}
})()
</script>
</html>