2013-08-27 5 views
10

を不発、のlocalStorage実装が予期せずに(ここでは偉大なスレッド:Bug with Chrome's localStorage implementation?を)イベントを発生IEのlocalStorageイベントは、Internet Explorer 9 & 10内

誰が変更を開始したタブに発射からstorageイベントを停止する方法を知っていますインターネットエクスプローラ内で?

追加ボタンをクリックしたときにたとえば、次のように警告を表示しないはずですが、それはIEで行います。

フィドル:http://jsfiddle.net/MKFLs/

<!DOCTYPE html> 
<html> 
    <head> 
    <title>Chrome localStorage Test</title> 
    <script type="text/javascript" > 

     var handle_storage = function() { 
     alert('storage event'); 
     }; 

     window.addEventListener("storage", handle_storage, false); 

    </script> 
    </head> 
    <body> 
    <button id="add" onclick="localStorage.setItem('a','test')">Add</button> 
    <button id="clear" onclick="localStorage.clear()">Clear</button> 
    </body> 
</html> 

はEDIT: サイドノートで、私は、ここMSにバグがありました。以下のスクリプトを変更するhttps://connect.microsoft.com/IE/feedback/details/798684/ie-localstorage-event-misfired

多分それが閉じ得ることはありません.....

+0

を:) – Jesse

答えて

11

は、フォーカスされたウィンドウ内の任意のストレージイベントの処理を防ぐことができます。

これはブラウザにパッチが必要だと思うので、あなたが尋ねたものではありませんが、IE 9/10は仕様に準拠していますが、他のブラウザ(グローバルリスナー)。

<script type="text/javascript" > 
     var focused; 

     window.addEventListener('focus', function(){focused=1;}, false); 
     window.addEventListener('blur', function(){focused=0;}, false); 

     var handle_storage = function (e) { 
     if(!focused) 
      alert("Storage",focused); 
     }; 

     window.addEventListener("storage", handle_storage, false); 

</script> 

更新された準拠の動作については、this fiddleを参照してください。

編集:以下も動作し、ウィンドウフォーカスのランタイムチェックのコストでリスナーを回避:

<script type="text/javascript" > 

     var handle_storage = function (e) { 
     if(!document.hasFocus()) 
      alert("Storage"); 
     }; 

     window.addEventListener("storage", handle_storage, false); 

</script> 
+0

一つは、追加の変数を必要としない:http://stackoverflow.com/a/8235434/255363(私がテストしました - これはIE9 +、ストレージイベントが出現したところで動作します) – kirilloid

0

あなたは回避策を探しているなら、あなたはセマフォとのlocalStorageのラッパーを書くことができます。

この(テストしていない)試してみてください:編集のための感謝@EricLaw

var BetterStorage = { 
    _semaphore: false, 
    setItem: function(key, item) { 
     var that = this; 
     this._semaphore = 1; // only this tab 
     localStorage.setItem(key, item); 
     this._semaphore = 0; 
     // or setTimeout(function(){that._semaphore = 0}, 10) 
     // based on event-fire time (immedietaly or after short delay?) 
     // not tested 
    }, 
    getItem: function() {/*code*/}, 
    createHandler: function(f) { 
     var that = this; 
     return function(e){ 
      if (that._semaphore) { // execution of event is blocked 
       return false; 
      } 
      else { 
       return f(e); 
      } 
     } 
    } 
} 


var handle_storage = BetterStorage.createHandler(function() { 
     alert('storage event'); 
}); 
window.addEventListener("storage", handle_storage, false); 
+1

この解決策は機能しません - setItemは完了し、イベントが発生する前に戻ります。したがって、セマフォはすでにクリアされています。 –

関連する問題