Search code examples
javascriptiframehtml5-videovideo.jslightgallery

How to restore focus to iframe's parent after user interaction?


I am using the LightGallery lightbox lib to play a video (using video.js) in an iframe. The esc key is used to close the LightGallery instance. This works fine until the user interacts with the video controls since those are given focus.

How can I restore focus to the LightGallery instance after these interactions?

I've been poking around video.js and am able to trap these user clicks but so far I haven't been able to figure out what I need to do to return focus so the esc key works. I've tried using postMessage, blur and everything else I could think of and I'm a little lost. Am I asking the wrong question/looking at the wrong thing?


Various attempts:

player.on('click', function (evt) {
        console.log('iframe window', window.frameElement);
        
        evt.currentTarget.blur();

        window.postMessage("hello", "*")
        // var lg = document.getElementById('vidContainer');
        // var lg = document.getElementsByClassName('lightGallery');
        // console.log('lg', lg);
        // console.log('document', document);
        // lg.focus()
      });

Solution

  • So I resolved the "focus" issue in what may be a really hacky way but it seems to work to insure that the lightbox close button can always be triggered by the escape key,

    1. When the iframe loads, store a reference to the close button in the parent window.

      let closeBtn
      
       window.onload = function () {
         closeBtn = parent.document.getElementsByClassName("lg-close lg-icon")[0]
       }
      

    1. Add a click event handler to the Videojs instance and use it to reassert focus on the close button after the user has interacted with the video controls. Not great, not accessibility friendly but this is what the client is expecting.

      player.on('click', function (evt) {
          closeBtn.focus();
      });