iframe和頁面處在不同域下,iframe操作頁面的屬性與方法
問題來源:
當(dāng)iframe和父頁面處在不同域下,會因?yàn)榭缬蛟斐上拗?,拿不到父頁面的大多?shù)屬性與方法
解決方案:
通過代理頁面解決跨域問題
1、在父頁面中設(shè)置一個(gè)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、然后在父頁面同一域下新建一個(gè)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頁面中創(chuàng)建一個(gè)看不見的iframe來加載這個(gè)代理頁面
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>