iframe和頁面處在不同域下,iframe操作頁面的屬性與方法

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>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容