localStorage实现缓存跨域共享
window.open + iframe+localstory实现缓存跨域–解决iframe打不开https页面的问题
首先如果iframe的IP端口和腹肌页面一致,不涉及跨域可以直接共享,如果不同就需要用文中的方式处理,我自己试着可行
不跨域
父级
<template>
<div class="h-full">
<iframe
id="bbb-iframe"
ref="iframeRef"
class="wh-full"
:src="src"
allowfullscreen
allow="autoplay;microphone;camera;midi;encrypted-media"
></iframe>
</div>
</template>
// 监听页面执行成功
window.addEventListener('message', receivemessage, false);
function receivemessage(event: any) {
localStorage.setItem('itemyl', event.data);
}
子级
mounted() {
localStorage.setItem("itemyl","dfs")
window.parent.postMessage(localStorage.getItem('itemyl'), 'http://父级ip:父级端口');
this.init();
},
跨域
因为https网页没有ssl证书不安全,在http的系统里面用iframe不能打开这种页面,
但是可以先在浏览器打开这个页面然后iframe就会加载这个页面。
这种情况下window.open打开的子页面 window.opener这个Window 对象的引用是获取不到的。
就可以用以下方式进行处理。
父页面
<template>
<div class="h-full">
<iframe
id="bbb-iframe"
ref="iframeRef"
class="wh-full"
:src="src"
allowfullscreen
allow="autoplay;microphone;camera;midi;encrypted-media"
></iframe>
</div>
</template>
<script setup lang="ts">
import { onMounted, nextTick, ref } from 'vue';
import { getServiceEnvConfig } from '~/.env-config';
const src = ref();
const iframeRef = ref(null);
const childWin = ref();
onMounted(() => {
nextTick(() => {
const itemval = window.localStorage.getItem('itemyl');
console.log(`itemval${itemval}`);
if (itemval !== 'dfs') {
window.name = window.location.pathname; // 这里使用浏览器路径作为 windowName
const childWinUse = window.open(
'https://192.168.1.126:9000/videoJJ.html',
//这个地方很奇怪,不是很明白,就是随便去写一个字符串作为window.open 的名字的时候,就不行,但是也不能直接用当前页面的window.name 所以后面就拼接了一个s,这样子页面的window.top就能用了
`${window.name}s`,
'height=400, width=550'
);
const intervalTemp = setInterval(() => {
// 设置一个interval,每隔1s去执行一次,为子页面添加opener属性值,获取到子页面已经关闭,则清除interval
if (childWinUse?.closed) {
console.log('en++++++++++++++++++++++++++++++++++++++++');
src.value = 'https://192.168.1.126:9000/videoJJ.html';
clearInterval(intervalTemp);
} else {
console.log('not---------------------------------------');
}
}, 1000);
} else {
src.value = 'https://192.168.1.126:9000/videoJJ.html';
}
});
});
// 监听页面执行成功
window.addEventListener('message', receivemessage, false);
function receivemessage(event: any) {
localStorage.setItem('itemyl', event.data);
}
</script>
<style scoped></style>
子页面
mounted() {
localStorage.setItem("itemyl","dfs")
window.top.postMessage(localStorage.getItem('itemyl'), '*');
this.init();
},
逻辑简单说一下,首先父页面初始化获取缓存,如果获取到的不是子级页面的缓存就,window.open一个页面,然后open的页面创建缓存并把缓存通过postMessage传递给父级。父级把子级的缓存存起来。父级有一个轮询,如果检测到自己页面关掉了,就把子级页面的地址赋值给父级的iframe,这样父级就可以打开子级的https页面了。