实现iframe共享cookie的问题

457 阅读2分钟

server.js

let Koa = require('koa')
let KoaRouter = require('koa-router')

/*
koa框架:用来搭建服务器,作用跟express一样
koa-router:koa的扩展库,相当于中间建,用来搭建注册路由
*/

//1  生成实例
const app = new Koa();
const router = new KoaRouter();

//3 声明路由
app
    .use(router.routes())
    .use(router.allowedMethods())
    

function getCookie (cname, cookie) {
    let name = cname + "=";
    let ca = cookie.split(";");
    for (let i = 0; i < ca.length; i++) {
        let c = ca[i].trim();
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
}
function setStorageCookie (cookies) {
    cookies.set('name', 'victor', {
        httpOnly: false,
        maxAge:'60 * 60 * 60 * 1000',
    });
    cookies.set('time', '123456789', {
        httpOnly: false,
        maxAge:'60 * 60 * 60 * 1000',
    });
}

function clearCookie (cookies) {
    cookies.set('name', '', {signed:false,maxAge:0});
    cookies.set('time', '', {signed:false,maxAge:0});
}

let dataJson = ['victor', 'victor1'];

function loginTemplate () {
    return `
        <!DOCTYPE html>
        <html>
            <head>
                <meta charset="utf-8">
                <title>一个简单的网页</title>
            </head>
            <body>
                <h6>父页面</h6>
                <div>
                    <button onclick="btnClick(3007)" >子页面1</button>
                    <button onclick="btnClick(3008)" >子页面2</button>
                </div>
                <div id="login">
                    <div>
                        登录页面
                    </div>
                    <input id="password" />
                </div>
                <div id="iframeContainer">
                    <iframe id="myFrame" src="http://localhost:3007" width="800px" height="350px"></iframe>
                </div>
                <script>
                    window.storageCookie =  document.cookie;
                    function btnClick(port) {
                        document.getElementById("myFrame").src = "http://localhost:" + port;
                        router();
                    }
                    function router () {
                        if (!window.storageCookie) {
                            document.getElementById("login").style.display = "block";
                            document.getElementById("iframeContainer").style.display = "none";
                        } else {
                            document.getElementById("login").style.display = "none";
                            document.getElementById("iframeContainer").style.display = "block";
                        }
                    }
                    function login () {
                        let password = document.getElementById("password");
                    }
                    function request (requestType, url, data) {
                        let xhr = new XMLHttpRequest();
                        xhr.open(requestType, url, true);
                        xhr.onreadystatechange = function() {
                            if (xhr.readyState == 4) {
                                if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                                    router();
                                } else {
                                    alert("Request was unsuccessful: " + xhr.status);
                                }
                            }
                            //发送请求
                            xhr.send(data);
                        }
                    }
                    router();
                    function handleEvent() {
                        // myFrame 的 id
                        var f = document.getElementById('myFrame');
                        // 触发子页面的监听事件
                        f.contentWindow.postMessage('父页面发的消息', '*');
                    }
                    // 注册消息事件监听,接受子元素给的数据
                    window.addEventListener('message', (e) => {
                        e.data.cookie = window.storageCookie;
                        console.log("父页面 = ", e.data);
                        var iframe = document.getElementById("myFrame");
                        iframe.contentWindow.postMessage(window.storageCookie, 'http:localhost:3007')
                    }, false);
                </script>
            </body>
        </html>
`;
}

//4 注册路由
router.get('/', (ctx, next) => {
    // 判断请求是否携带cookie并且判断coolie是否过期
    console.log('xxxxxxx', dataJson.indexOf(ctx.cookies.get('name')));
    if (ctx.cookies.get('name') && dataJson.indexOf(ctx.cookies.get('name')) === -1) {
        clearCookie(ctx.cookies);
    } else {
        setStorageCookie(ctx.cookies);
    }
    ctx.body = loginTemplate()
});

router.get('/login', (ctx, next) => {
    // 判断请求是否携带cookie并且判断coolie是否过期
    console.log('xxxxxxx', dataJson.indexOf(ctx.cookies.get('name')));
    if (ctx.request) {
        setStorageCookie(ctx.cookies);
    }
    ctx.body = loginTemplate()
});

//2  监听端口
app.listen('3006',(err)=>{
    if(err){
        console.log('服务器失败')
    }else{
        console.log('服务器启动成功:地址为:http://localhost:3006')
    }
})

server1.js

let Koa = require('koa')
let KoaRouter = require('koa-router')

/*
koa框架:用来搭建服务器,作用跟express一样
koa-router:koa的扩展库,相当于中间建,用来搭建注册路由
*/

//1  生成实例
const app = new Koa()
const router = new KoaRouter();

//3 声明路由
app
    .use(router.routes())
    .use(router.allowedMethods())
   
//4 注册路由
router.get('/', (ctx, next) => {
    ctx.body = `
        <!DOCTYPE html>
        <html>
            <head>
                <meta charset="utf-8">
                <title>一个简单的网页</title>
                <script>
                    window.a = {};
                    console.log("xxxxxxxxxxxxxxxxxxxxx");
                    console.log("window.parent = ", window.parent);
                    function myFunction() {
                        window.parent.postMessage(a, '*');
                    }
                    window.addEventListener('message',e=>{
                       console.log('子页面接收 = ', e.data)  //父页面发送的消息
                   }, false)
                </script>
            </head>
            <body onload="myFunction()">
                <h6>子子子子子子子子子子子子子子子子子子子111</h6>
            </body>
        </html>
    `;
});

//2  监听端口
app.listen('3007',(err)=>{
    if(err){
        console.log('服务器失败')
    }else{
        console.log('服务器启动成功:地址为:http://localhost:3007')
    }
})

server2.js

let Koa = require('koa')
let KoaRouter = require('koa-router')

/*
koa框架:用来搭建服务器,作用跟express一样
koa-router:koa的扩展库,相当于中间建,用来搭建注册路由
*/

//1  生成实例
const app = new Koa()
const router = new KoaRouter();

//3 声明路由
app
    .use(router.routes())
    .use(router.allowedMethods())
   
//4 注册路由
router.get('/', (ctx, next) => {
    ctx.body = `
        <!DOCTYPE html>
        <html>
            <head>
                <meta charset="utf-8">
                <title>一个简单的网页</title>
                <script>
                    
                </script>
            </head>
            <body>
                <h6>子子子子子子子子子子子子子子子子子子子222</h6>
            </body>
        </html>
    `;
});

//2  监听端口
app.listen('3008',(err)=>{
    if(err){
        console.log('服务器失败')
    }else{
        console.log('服务器启动成功:地址为:http://localhost:3008')
    }
})