Detecting when an iframe gets or loses focus

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

    You can poll "document.activeElement" to determine if it matches the iframe. Polling isn't ideal, but it works:

    function checkFocus() {
      if(document.activeElement == document.getElementsByTagName("iframe")[0]) {
        console.log('iframe has focus');
      } else {
        console.log('iframe not focused');
      }
    }
    
    window.setInterval(checkFocus, 1000); 
    

提交回复
热议问题