本地JS - 发送
// 登录
$(".login").click(function () {
location.href = "https://xxxx.com/login?website="+location.origin;
});
Vue - src/router/index.js
// 官网间接登录
router.beforeEach((to, from, next) => {
if(to.query.website) {
let websiteUrl = to.query.website;
localStorage.setItem("websiteUrl",websiteUrl);
// 判断本页面是否已登录 - 未登录
let token = localStorage.getItem("token");
if(token) {
const targetWindow = window.open(localStorage.getItem("websiteUrl"));
setTimeout(() => targetWindow.postMessage(token,websiteUrl), 1000);
}
}
});
// 官网间接登录
const targetWindow = window.open(localStorage.getItem("websiteUrl"));
setTimeout(() => {
targetWindow.postMessage(localStorage.getItem("token");, localStorage.getItem("websiteUrl"))
}, 1000);
本地JS-接收返回
/**
* postMessage
* 接收消息 xxxx.com 登录 token
*/
window.addEventListener('message', event => {
// 检查消息来源是否合法,避免受到跨站点攻击
if (event.origin !== 'https://xxxx.com') {
localStorage.setItem("token", event.data);
}
// 反向发消息给发送消息的窗口
// e.source.postMessage('来自10001的消息', e.origin)
});