Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding focused item in iframe

I'm trying to find the focused item within an iframe but failing!

Whenever I insert into the iframe the item appears to be focused, for example if I insert a table then the cursor is always in the last cell.

As a I test I am trying to change the background color of the cell to see if it is working but this always changes the iframe body not the item inserted

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 call of a function that uses the execCommand() to insert into the iframe.

Is it at all possible to find the focused element and store it in this method?

like image 379
JQuery Avatar asked Oct 29 '22 08:10

JQuery


1 Answers

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

There may be no element focused; when no element is focused, key events received by the document must be targeted at the body element, if there is one, [...] User agents [...] may support only one focused element per top-level browsing context — user agents should follow platform conventions in this regard.

See also the CSS :focus selector. Your problem is that only one element in the whole browsing context can have focus. If the focus is not within the iframe, it is somewhere else, and the iframe's body element is that fallback.

https://www.w3.org/TR/html5/browsers.html#nested-browsing-context says that iframes are nested browsing contexts, not top-level browsing contexts. So is seems as though there's only one focused element for the whole page. If that is not within your iframe, its body is returned instead.

like image 195
serv-inc Avatar answered Nov 15 '22 11:11

serv-inc