iframe 页面中获取父级页面的 localStorage 或者 sessionStorage数据

您所在的位置:网站首页 java获取sessionstorage值 iframe 页面中获取父级页面的 localStorage 或者 sessionStorage数据

iframe 页面中获取父级页面的 localStorage 或者 sessionStorage数据

2024-07-05 05:17| 来源: 网络整理| 查看: 265

问题

在开发的过程中遇到需要在 iframe 页面中获取父级页面系统所存储的本地数据的需求。由于浏览器的安全策略,是不允许 iframe 页面直接获取系统的存储数据的,那么要如何解决呢?

解决方法

对于该问题,我们可以通过 window.postMessage() 传值来解决。

window.postMessage() 方法允许来自一个文档的脚本可以传递文本消息到另一个文档里的脚本,而不用管是否跨域。一个文档里的脚本还是不能调用在其他文档里方法和读取属性,但他们可以用这种消息传递技术来实现安全的通信。

实现代码

1、父级页面在 iframe 加载完成后,使用 postMessage 方法将存储的数据发送给 iframe 。

父级页面代码:

var data = { 'localStorage': localStorage.getItem('key'), 'sessionStorage': sessionStorage.getItem('key') }; var iframe = document.getElementById('myIframe'); iframe.onload = function() { iframe.contentWindow.postMessage(JSON.stringify(data), '*'); };

2、在 iframe 中,通过监听父级的 message 事件,获取发送过来的数据。

iframe 页面代码:

window.addEventListener('message', function(event) { var data = JSON.parse(event.data); var localStorageValue = data.localStorage; var sessionStorageValue = data.sessionStorage; console.log(localStorageValue); // 输出localStorage的值 console.log(sessionStorageValue); // 输出sessionStorage的值 });

这样就实现了 iframe 页面中获取父级页面系统所存储的本地数据的需求了。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3