Finding a focused object in an iframe

I am trying to find a focused element in an iframe but it fails!

Whenever I insert in an iframe, the element seems focused, for example, if I insert a table, then the cursor is always in the last cell.

As test I, I try to change the background color of the cell to see if it works, but this always changes the body of the iframe, not the inserted element

var d1 = $.Deferred(); $.when(d1).then(function () { var $iframe = $("#ifr").contents(); var focused = $iframe.find(':focus'); focused.css("background", "red"); console.log(focused); }) d1.resolve(insertTable(html)); 

d1 is just a function call that uses execCommand () to insert into an iframe.

Is it possible to find a focused element and save it in this method?

+5
source share
2 answers

The body element is fallback if the other element has no focus :

There can be no targeted element; when no element is focused, the key events received by the document should be aimed at the body element, if it exists, [...] User agents [...] can support only one focused element at the top level of the viewing context . User agents must follow platform conventions in this regard.

See also CSS :focus selector . Your problem is that only one element in the entire viewing context can have focus. If the focus is not inside the iframe , it is somewhere else, and the iframe body is the backup.

https://www.w3.org/TR/html5/browsers.html#nested-browsing-context says iframe are nested view contexts, not top-level view contexts. There seems to be only one focused element for the whole page. If this is not included in your iframe , body returned instead.

+2
source

Put this script on your iframe page.

 $("body").delegate( "*", "focus blur", function() { var elem = $( this ); setTimeout(function() { elem.toggleClass( "focused", elem.is( ":focus" ) ); }, 0 ); }); 

An example iframe page is

 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> .focused {background: #F00;} </style> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <form action="#"> First name:<br><input type="text" name="firstname" value="Mickey" > <br> Last name:<br><input type="text" name="lastname" value="Mouse"> <br><br><input type="submit" value="Submit"> </form> <script> $("body").delegate( "*", "focus blur", function() { var elem = $( this ); setTimeout(function() { elem.toggleClass( "focused", elem.is( ":focus" ) ); }, 0 ); }); </script> </body> </html> 
0
source

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


All Articles