Detecting when an iframe gets or loses focus

前端 未结 9 1269
我寻月下人不归
我寻月下人不归 2020-12-31 06:24

What\'s the correct way of detecting when an iframe gets or loses focus (i.e. will or will not receive keyboard events)? The following is not working in Fx4:



        
相关标签:
9条回答
  • 2020-12-31 07:02

    Turns out it's not really possible. I had to change the logic of my page to avoid the need of tracking if the iframe has focus.

    0 讨论(0)
  • 2020-12-31 07:05

    This solution is working for me on both mobile and desktop:

    ;(function pollForIframe() {
      var myIframe = document.querySelector('#my_iframe');
      if (!myIframe) return setTimeout(pollForIframe, 50);
    
      window.addEventListener('blur', function () {
        if (document.activeElement == myIframe) {
          console.log('myIframe clicked!');
        }
      });
    })();
    
    0 讨论(0)
  • 2020-12-31 07:06

    Here is the code to Detecting when an iframe gets or loses focus

     // This code can be used to verify Iframe gets focus/loses.
    
          function CheckFocus(){
    
           if (document.activeElement.id == $(':focus').context.activeElement.id) {
                    // here do something
                }
         else{
          //do something
        }
    }
    
    0 讨论(0)
提交回复
热议问题