How to work around IE11 localStorage events firing twice or not at all in iframes?

感情迁移 提交于 2019-12-03 04:13:08

If you ever want to throttle an event from being called multiple times, regardless the cause for invocation, use a flag to block subsequent events. There are several strategies:

.1. time-based throttling. suppose you have a function "func", and you'd like it to be called only once within 200ms:

function func(){
  if (document.func_lock) return;
  document.func_lock=true; // block future calls
  setTimeout(function(){document.func_lock=null;},300);
}

When multiple events are fired at the same time, you can expect all of them arrive within the 300ms window. The above code can be simplified by taking advantage of the timer handle:

function func(){
  if (document.func_lock) return;
  document.func_lock=setTimeout(function(){return;},300);
}

When the timer expires, the lock is automatically removed.

.2. Remove the flag by using a callback. The process is trivial so I won't post sample code here.

In terms of flag placement, you can use any unique DOM object. Since I don't know the context of your application, I'll just use "document" here. You can also use hash keys that are particular to your application since you are already dealing with local storage. The concept is the same.

I was able to work around the issue by using window.parent to register the event in the iframe in this way:

Iframe page

var win = window.parent || window.opener || window;
win.addEventListener('storage', handleLocalStorageEvent, false);

function handleLocalStorageEvent(e) {
    console.log('IFRAME local storage event', e);

    var sdf = document.getElementById('sdf');
    sdf.innerHTML = sdf.innerHTML + 'Storage Event => (' + e.newValue + ')<br>';
}

Disclaimer: Please note that this solution is meant to fix(work around) IE11 issue. By any means it is intended or suggested that this applies to all browser.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!