You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从iframe触发的同域弹窗无法访问localStorage?跨源嵌入场景原因排查

问题

在X域的网页中嵌入了一个Y域的iframe,该iframe加载时会设置localStorage键“abc”;点击iframe内的按钮后,会打开一个指向Y域的弹窗,但这个弹窗无法访问iframe设置的localStorage。不过如果直接在新浏览器窗口中打开iframe.htm(而非嵌入到X域网页),弹窗就能正常读取到localStorage。请问这是否由特定安全策略导致?

示例代码

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>
<!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>
解答

这是由浏览器的第三方存储隔离策略导致的,本质是同源策略在第三方上下文场景下的延伸限制:

  1. 第三方上下文的存储隔离
    当Y域的iframe被嵌入到X域页面中时,该iframe处于第三方上下文(主页面域为X,iframe域Y属于第三方)。主流浏览器为保护用户隐私,会对第三方上下文的存储做隔离处理——此时iframe设置的localStorage会被标记为Y域的第三方存储空间,和Y域作为第一方(直接打开Y域页面)时的存储空间完全独立。

  2. 弹窗的上下文继承
    从第三方上下文的iframe中通过window.open打开的Y域弹窗,会继承这个第三方上下文属性,它访问的是Y域的第三方存储空间,而非第一方存储空间。而iframe设置的"abc"仅存在于自身所在的第三方存储中,弹窗无法跨上下文访问该空间的内容。

当直接打开Y域的iframe.htm时,页面处于第一方上下文,设置的localStorage属于Y域的第一方存储;通过它打开的弹窗也是同域第一方上下文,自然能正常读取到该存储内容。

内容的提问来源于stack exchange,提问作者JasonBourne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 20:13:20