Trigger click on iframe

I am aware of a politics of the same origin ... just misguided.

Anyway, I have a slide show (slide.js) in which there are embedded videos. When a user clicks on a video, I want the slide show to pause. Events from inside the iframe do not fire, so I'm trying to get around this. Now I have a partial solution. I detect a blur event on the window , and if the newly focused element is an iframe , I pause the slide show:

 $(window).blur(function(event){ console.log(event.target); if($('iframe').is(':focus')){ //clicked inside iframe console.log('test'); } console.log('document.activeElement is:'); console.log(document.activeElement); console.log('\n'); }); 

After loading the page, I get this in the console:

 document.activeElement is: BODY 

Now part of me is embarrassing. The click event only fires the iframe focus event when I first click somewhere other than the iframe . That is, after loading the page, if I directly click on the iframe, the console does not check the log. If I click on the outer frame or another tab in the browser or elsewhere, the blur event will occur. After that, if I click on the iframe, I will get the test in the console:

After loading the page, I click another tab and then return to the original tab:

 Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…} document.activeElement is: <body class="full">...</body> 

Then I click iframe:

 Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…} test document.activeElement is: <iframe>...</iframe> 

Why???

I even put this in front of everything and it did not help:

 $(window).focus(); 

However, it works if I do this:

 $('input').focus(); 

If the input is focused, then I can click on the iframe and fire the event without first clicking on anything else.

Help me, you are my only hope ...

+4
source share
3 answers

EDIT:

Actually, just using native window.focus() seems to work for me:

Fiddle


How to simply add another element to set focus:

 $('<input>', {type: 'text', style: 'top: -10000px; position: absolute', autofocus:true} ).appendTo('body') .focus(); // just to make sure 

Fiddle

If you can, I would add an autofocus input element directly to the markup, so the blur event always fires the first time it is clicked.

Fiddle

0
source

May be a workaround:

 $(window).load(function () { $('body').prop('tabindex', -1).focus(); }); 
0
source

Depending on what kind of video service you are using, it would be better to use their video API. Then you can receive video events and know exactly when to pause and / or resume the slide show.

  • YouTube API ( demo )

     <script src="http://www.youtube.com/iframe_api"></script> 
  • Vimeo API (good demo using Froogaloop)

     <script src="http://a.vimeocdn.com/js/froogaloop2.min.js"></script> 
0
source

Source: https://habr.com/ru/post/1480780/


All Articles