要做的是两个跨域页面传输传大量的数据,由于url有长度限制,所以拼接的方式行不通,后来查到可以用postmessage来做:
<iframe
id="myIframe"
style="display: none"
:src="ifSrc"
frameborder="0"
></iframe>
在页面中添加一个iframe标签并隐藏,这里src为为另一个项目的地址;
我最开始想的是,src不能写死,后期肯定会变的,所以就用变量,
后俩就遇到了问题
Failed to execute ‘postMessage’ on ‘DOMWindow’: The target origin provided (‘http://192.168.2.28:83’) does not match the recipient window’s origin (‘http://127.0.0.1:8082’).
这个问题的原因是,我使用postMessage时候,iframe页面还未创建,
我的写法为:
ifSrc: "", // iframe 地址
-----------------------------------------------------------
var myIframe = document.querySelector("#myIframe");
if (myIframe) {
that.ifSrc='http://192.168.2.28:83/CreateScenario'
var data = { value, id: that.scenarioId, name };
myIframe.contentWindow.postMessage(
JSON.stringify(data),
`${ that.ifSrc}`
);
解决方案有两种,
其一为,提前赋予iframe src具体值,使页面创建
其二为,给代码加一个延时
setTimeout(() => {
myIframe.contentWindow.postMessage(
JSON.stringify(data),
`${ that.ifSrc}`
);
}, 500);
我的选择是,方法一, 提前赋予src,
ifSrc: "http://192.168.2.28:83/CreateScenario", // iframe 地址
---------------------------------------------------------
if (myIframe) {
var data = { value, id: that.scenarioId, name };
setTimeout(() => {
myIframe.contentWindow.postMessage(
JSON.stringify(data),
`${ that.ifSrc}`
);
}, 500);
window.open(`${ that.ifSrc}`);
}
后面如果地址有变动的话,也可直接修改,没有其他影响
附上 两个跨域页面进行跳转传参的终极方案
https://www.jianshu.com/p/6be6c3f2867a