Why does YouTube IFrame having focus break PostMessage (tip for YouTube IFrame user)

Although this is not specifically a ThreeJS question, it does happen to me while trying to use a CSS3DRenderer object hosting a YouTube IFrame displayed on a ThreeJS cube surface.

For a whole day I could not get things working and went through a lot of painful permutation paths trying to get it to work. Today I discovered what was wrong. So I want to share the solution in case it happens to someone else. And I would also appreciate it if anyone can tell me why it works?

For some truly bizarre reason, The YouTube IFrame, at least for me, will not respond to a postMessage command if it currently has focus. Once I took focus away from the IFrame right before sending the postMessage message, everything worked fine. I do this by calling blur() on the IFrame’s contentWindow property as shown below:

        // You must take focus *away* from the IFrame's contentWnidow object 
        //  before calling postMessage or it will not do anything in response to the call.

        // Post it to the YouTube video IFrame object.
        self.youTubeIFrameObj.contentWindow.postMessage(msgToSend, '*');

Can anyone explain to me why this “hack” works?

Does it behave the same without CSS3D?

Yes. As I said, I don’t think it’s a ThreeJS issue. I’m just trying to understand what the YouTube IFrame is doing to “get in the way”. I’d like to add some code to my ThreeJS code that I use between all my projects to automatically compensate for this so I don’t have to revisit this problem in the future. Plus, I’d just like to know what is going on.

Consider to ask the question at stackoverflow where you can reach more “classic” web devs. In this way, you potentially reach more people who might know the answer.

1 Like