window.open() jumps to other systems, and the parameters are not placed on the URL

在Vue中,可以使用window.open()和postMessage方法实现在跳转其他系统时不暴露参数的需求。
第一步:在发送数据的系统中使用以下代码:
const data = { username: 'test', age: 18 };
const targetUrl = 'http://other-system.com';
const childWindow = window.open(targetUrl, '_blank');
setTimeout(() => {
  childWindow.postMessage(data, targetUrl);
}, 1000);

这里使用了window.open()方法打开一个新窗口,并在1秒后通过postMessage()方法向该窗口发送数据。第二个参数是目标地址,在接收数据的系统中需要用到。
第二步:在接收数据的系统中使用以下代码:
window.addEventListener('message', function(e) {
  if (e.origin !== 'http://sending-system.com') return; // 检测数据来源
  const data = e.data;
  console.log(data.username); // 'test'
  console.log(data.age); // 18
});

在接收数据的系统中使用DOM API的postMessage事件监听器来检测从发送系统发送的消息。在接收到数据时,我们可以使用e.data来访问发送的数据。需要注意的是,我们可以使用e.origin来检测数据是否来自预期的来源。
这样,我们就可以通过window.open()和postMessage()方法在两个系统之间安全地传递数据了。

Guess you like

Origin blog.csdn.net/yf18040578780/article/details/129840309
Recommended