Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focus in an iframe in Firefox

I shall open a dialog which contains an iframe, then set the focus inside the iframe once the dialog is opened.

Currently, I try to get the focus on the iframe when the content is loaded:

<iframe src="../credits.html" onload="this.contentWindow.focus()"></iframe>

It works fine for all browsers except for Firefox, and I don't understand why.

Can someone tell me why? Thanks

like image 205
Guern Avatar asked Jan 17 '13 10:01

Guern


People also ask

Does iframe work in Firefox?

Contents of iframe works well in chrome but not in firefox.


2 Answers

Firefox seems not to have contentWindow property, you should use contentDocument

Update:

After a small debate I came up with a better solution:

<html>
<head>
  <title></title>
  <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
  <script type="text/javascript">
$(function() {
    $("#xframe").bind("load", function(){
        $(this).contents().find("#xa").focus();
    });
});

  </script>
</head>
<body>
<iframe id="xframe" src="./y.html"></iframe>
</body>
</html>

In this example, I assume that there's a input field inside y.html that has a "xa" id. It worked both on Chrome and Firefox.

Old answer

Even better you should use jquery, something like:

<html>
<head>
  <title></title>
  <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
  <script type="text/javascript">
   $(document).ready(function() {
    $("#xframe").focus();
   });
  </script>
</head>
<body>
<iframe id="xframe" src="./y.html"></iframe>
</body>
</html>

Of course you could do some extra check to see if the iframe is ready.

More info can be found here http://www.w3schools.com/jsref/prop_frame_contentwindow.asp

like image 175
rfsbsb Avatar answered Sep 27 '22 22:09

rfsbsb


Try do this using jquery

  // focus an input in iframe
 $('#xframe').contents().find('input').get(0).focus()


 // or simply iframe window
var iframe= $('#xframe')[0];
var iframewindow= iframe.contentWindow?     iframe.contentWindow :     iframe.contentDocument.defaultView;
iframewindow.focus()
like image 45
Sergiu Gordienco Avatar answered Sep 27 '22 21:09

Sergiu Gordienco