Focus in iframe in Firefox

I will open a dialog box that contains an iframe, and then set the focus inside the iframe after opening the dialog.

I'm currently trying to focus on iframe when loading content:

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

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

Can someone tell me why? Thanks

+8
javascript firefox iframe onload focus
source share
2 answers

Firefox doesn't seem to have a contentWindow property, you should use contentDocument

Update

After a little discussion, 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 is an input field inside y.html that has the identifier "xa". It worked in both Chrome and Firefox.

Old answer

Better yet, 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 can do extra checking to make sure the iframe is ready.

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

+3
source share

Try to do it with 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() 
+1
source share

All Articles