如何从 iframe 生成的弹出窗口访问本地存储

问题描述 投票:0回答:1

在属于原点 X 的网页上,我有一个属于原点 Y 的 iFrame。iFrame 中有一个按钮,用于打开一个弹出窗口,该窗口导航到属于域 Y 的网页。当 iFrame 页面加载时,它会设置一个本地存储密钥“abc”。但是,我无法从弹出窗口访问 iFrame 的本地存储。发生这种情况是否有任何特定的安全策略原因?

示例代码:

iFrame.htm:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        const setKey = ()=>{
            localStorage.setItem("abc","Good day")
        }
        const openPopup = ()=>{
            window.open("popup.htm","_blank","popup,left=100,top=100,width=320,height=600")
        }
    </script>
</head>
<body onload="setKey()">
    <h1> iFrame </h1>
    <button onclick="openPopup()"> Open popup </button>
</body>
</html>

弹出.htm:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        const accessStorage = ()=>{
            const abc = localStorage.getItem("abc")
            console.log(abc) //Null
        }
    </script>
</head>
<body onload="accessStorage()">
    <h1> Popup</h1>
</body>
</html>

令人惊讶的是,如果我在新的浏览器窗口中打开 iframe.htm 而不是将其嵌入到属于域 X 的网页中,则效果非常好。

javascript local-storage
1个回答
0
投票

从我的尝试和所做的来看,这似乎不可能。这就好像浏览器将 iframe 的数据容器化,并且不允许从其他页面访问它,即使它们来自同一来源。你可能不走运。

© www.soinside.com 2019 - 2024. All rights reserved.