1. 程式人生 > >window.name 實現跨域

window.name 實現跨域

window物件有一個name屬性,該屬性有一個特徵:即在一個視窗的生命週期內,視窗載入的所有的頁面都是共享一個window.name的,每一個頁面對window.name都有讀寫的許可權,window.name是持久的存在於一個視窗載入的所有頁面中的,並不會因為新的頁面的載入而被重置。

下面用專案中遇到的例項,講解如何用window.name實現跨域獲取資料。

專案需求:網站A與網站B互相跳轉,如使用者在網站A中已登入,跳轉到網站B時也要是已登入狀態。

第一步、在網站A點選跳轉地方,設定window.name

<a :href="sbUrl" @click="jump">申報</a>

  

mounted() {
        if (location.hostname == 'localhost') this.sbUrl = 'http://localhost:8080/#/';  //專案有分本地環境、測試環境、UAT環境、正式環境,因此跳轉的路徑要分情況處理
        else if (location.hostname == 'uatevaluate.bysxzx.com') this.sbUrl = 'http://uattest.bysxzx.com/#/';
        else if (location.hostname == 'devtest.bysxzx.com') this
.sbUrl = 'http://devtest.bysxzx.com/#/'; else if (location.hostname == 'evaluate.bysxzx.com') this.sbUrl = 'http://bysxzx.com/#/'; }, methods:{ jump(){ window.name = ''; if (!localStorage.getItem('token')) { //token獲取得到,說明已登入 window.name = 'logout'; }
else { window.name = JSON.stringify({ userId: localStorage.getItem('userId'), token:localStorage.getItem('token'), userType:localStorage.getItem('userType'), userData:localStorage.getItem('userData'), userInfo:localStorage.getItem('userInfo'), oldHref:localStorage.getItem('oldHref'), href:location.href}); localStorage.removeItem('oldHref'); } }, }

第二步:在網站B中獲取window.name

mounted: function(){
        if (window.name.length > 10) {   //如果window.name獲取得到,就說明該頁面是跨域過來的
            let udata = JSON.parse(window.name);
            localStorage.setItem('userId', udata.userId);   //專案需求是,如果已登入狀態之間的跳轉,需要把使用者資訊傳遞過去。因此要把使用者資料提取後存到localStorage,使跳轉後的網站登入介面能獲取到相關的資料,實現無縫登入
            localStorage.setItem('token', udata.token);
            localStorage.setItem('userType', udata.userType);
            localStorage.setItem('userData', udata.userData);
            localStorage.setItem('userInfo', udata.userInfo);
            this.isLogin = true;  //控制html中登入按鈕是否出現,true:不出現
            window.name = "";     //把window.name清空
            if (udata.oldHref) location.assign(udata.oldHref);
            localStorage.setItem('oldHref', udata.href);
        }
        if(localStorage.getItem('token')){  //以下兩種情況與跨域無關
            this.isLogin = true
            this.getUserInfo(localStorage.getItem('userId'))
        } else {
            this.isLogin = false
        }
    },