需要の背景:
複数のアイテム(同じトップレベルドメイン.scc.com)を使用すると、複数のタブページを開いたとき、私は、ログインページにあった、あり、他のページの同期情報ページポップアッププロンプトがログアウトされました。
実装はiframe +のpostMessage +のlocalStorage
3ページA1 A2 B1が着弾した場合
ページA1:http://a1.scc.com
ページA2:http://a2.scc.com
ページB1:http://b1.scc.com
空のiframeページ:http://static.scc.com/iframe.html
http://static.scc.com/iframe.htmlは、以下の
<HTML> <BODY> <SCRIPT> window.addEventListener( "ストレージ"、関数(EV){ EV = window.event || EV (ev.key == "scc_message"){もし window.parent.postMessage(EV。 newValueに、 "*"); } }); 関数postMessageToStorage(メッセージ){ localStorage.setItem( "scc_message"、JSON.stringify(メッセージ))。 localStorage.removeItem( "scc_message"); } window.addEventListener( "scc_message"機能(EV){ EV = window.event || EV せてデータ= ev.data。 postMessageToStorage(データ)。 }); </スクリプト> </ BODY> </ HTML>
コードA1 A2 B1、同じページ
DOM導入iframeタグ
<アイフレームID = "sccproxy" SRC = "// static.scc.com/iframe.html"スタイル= "幅:0PX;高さ:0PX; FRAMEBORDER:0"> </アイフレーム> <divのV-IF =のフラグ" > <H3> <I> </ I> <span>のログイン状態が変更されている</ span>を</ H3> <P->現在のアカウントのログイン状態が変化した、ページでリフレッシュすることについて。</ p型> の<div> <A HREF = "/"> OK </a>の</ div> </ div>
<ボタン@ =をクリックして"sendMessageToTab({タイプ: '' sccExit})">ログイン<ボタン>
JSコード
データ(){ リターン{ フラグ:偽 } } 搭載(){ this.addMessageListener() }、 メソッド:{ addMessageListener(){ _thisは=このせ window.addEventListener( "メッセージ"機能(EV){ EV =ウィンドウ。イベント|| EV せたデータ= ev.data; ソース= ev.sourceを聞かせ; 起源= ev.originを聞かせ; (!データ)であればリターン; 場合(origin.indexOf( "// static.scc.com")> = 0){ 試みは{ ;情報= JSON.parse(JSON.parse(データ))しましょう (もし!info.type == "sccExit" && document.hasFocus()){ _this。フラグ=真 } }キャッチ(E){ にconsole.log(E) } } })。 }、 sendMessageToTab(データ){ 試み{ document.querySelector( "#1 sccproxy")contentWindow.postMessage(JSON.stringify(データ)、 'http://static.scc.com')。 }キャッチ(ERR){ にconsole.log(ERR) } } }