Detecting when an iframe gets or loses focus

前端 未结 9 1339
我寻月下人不归
我寻月下人不归 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 06:43

    A compact function that accepts callbacks you want to run when iframe gets or loses focus.

    /* eslint-disable no-unused-vars */
    export default function watchIframeFocus(onFocus, onBlur) {
      let iframeClickedLast;
    
      function windowBlurred(e) {
        const el = document.activeElement;
        if (el.tagName.toLowerCase() == 'iframe') {
          iframeClickedLast = true;
          onFocus();
        } 
      }
      function windowFocussed(e) {
        if (iframeClickedLast) {
          iframeClickedLast = false;
          onBlur();
        } 
      }
      window.addEventListener('focus', windowFocussed, true);  
      window.addEventListener('blur', windowBlurred, true);
    }
    

提交回复
热议问题