iframe页面Storage数据共享

最近开发使用了iframe做跨系统,跨页面交互,当前页面存在多个iframe页面,并且每个iframe链接,同域。有些iframe 页面会有报错提示。

iframe(vue页面)具体加载逻辑,

  • iframe onload 之后 父页面 发送postMessage,
  • iframe 页面拿到message 保存在 sessionStorage中,
  • iframe 加载vue 页面时,查看sessionStorage 相关key 是否有 message
  • 存在,则使用该message,然后并清除

问题点

  • 当第一个iframe 加载vue 页面,并使用sessionStorage的值 时,可能是第二iframe 发送的。
  • 第一个iframe 使用 sessionStorage中 message 马上清除,
  • 第二个iframe 也开始加载vue 页面,正好 message 被清除,拿不到值,就报街廓错误

原因

同一个浏览器窗口下,多个iframe页面,同域下,Storage 是共享(即 sessionStorage 和 localStorage),iframe 页面相互影响


浮现例子

使用 http-server 启动 端口 3201

http-server -p 3201 -c-1

index.html

<!DOCTYPE html>
<html>
    <head></head>
    <body style="padding-top: 50px;">
        <div id="app">
                存在两个iframe 页面
        </div>

        <div style="margin-top: 40px;">第一个iframe</div>
        <iframe style="width: 300px; height: 200px;" src="http://172.19.4.113:3201/iframe.html"></iframe>
    

        <div style="margin-top: 40px;">第一个iframe</div>
        <iframe style="width: 300px; height: 200px;" src="http://172.19.4.113:3201/iframe.html"></iframe>
        </script>
    </body>
</html>

iframe.html

<!DOCTYPE html>
<html>
    <head></head>
    <body style="padding-top: 50px;">
        <div id="app"></div>
        <div id="appLocal"></div>
        <script>
            handleStorage('app','key',sessionStorage);
            handleStorage('appLocal','Localkey',localStorage);
            function handleStorage(ele,key,storage){
                var div = document.getElementById(ele);
        
                var keyValue = storage.getItem(key);
                if(keyValue){
                    keyValue = (+keyValue) + 1;
                }else {
                    keyValue = 1;
                }
                div.innerHTML =  `${key}==== ${keyValue}`;
                storage.setItem(key,keyValue);
            }
        </script>
    </body>
</html>
Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐