iframe 跨域之间共享localStorage,sessionStorage

时间:2025-03-05 07:06:48
 

如: 中读取的localStorage

9-1 实现原理:

1-1.在的页面中,在页面中嵌入一个src为的iframe,此时这个iframe里可以调用的localStorage。

1-2.用postMessage方法实现页面与iframe之间的通信。

综合1、2便可以实现中调用的localStorage

9-2优化iframe:

2-1我们可以在中写一个专门负责共享localStorage的页面,例如叫做,这样可以防止无用的资源加载到iframe中。

9-3 示例:

3-1 以在中读取中的localStorage的item1为例,写同理:

中,监听通过postMessage传来的信息,读取localStorage,然后再使用postMessage方法传给的接收者。

<!DOCTYPE html>

<html lang="en-US">

<head>

<script type="text/javascript">

('message', function(event) {

if ( === '') {

const { key } = ;

const value = (key);

({wallets: wallets}, );

}

}, false);

</script>

</head>

<body>

This page is for sharing localstorage.

</body>

</html>

3-2 在的页面中加入一个src为/隐藏的iframe。

<iframe src="/" style="display:none;"></iframe>

3-3 在的页面中加入下面script标签。在页面加载完毕时通过postMessage告诉iframe中监听者,读取item1。监听传回的item1的值并输出。

<script type="text/javascript">

= function() {

const bbbIframe = ('bbb-iframe');

({key: 'item1'}, '');

}

('message', function(event) {

if ( === '') {

();

}

}, false);

</script>