1

I am showing an external webpage inside an iframe and I want to set focus directly to the content of the webpage, the content is at the middle of the web page.

How can I achieve that?

Thanks

Banana
  • 7,424
  • 3
  • 22
  • 43
Nadir
  • 126
  • 1
  • 11

1 Answers1

1

If the page is on another domain you'll run into XSS (cross-site-scripting) issues and barriers put up by the browsers to avoid malicious manipulations!

If you are serving the page yourself you can do this:

inner.html:

<!doctype html>
<html>
<head><title>the iframe</title></head><body>
Hello World!<br/>
This is where we start to select something ..<br/>
.. right here: <input type="text" id="toBeSelected" size="12" value="this is to be selected" onfocus="this.select()"/><br/>
</body>
</html>

outer.html:

<!doctype html>
<html>
<head><title>fun with IFRAME</title></head><body>
<ol type="i">
<li>wait for loading..</li>
<li>..<a href="#" id="andThen" style="display: none;" onclick="setFocus(); return false;">set focus</a></li>
<li>..see the effect.</li>
</ol>
<iframe id="theIFRAME" width="500" height="500" frameborder="1" data-src="inner.html" style="margin: 1em auto 0;">NO IFRAME support</iframe>
<script type="text/javascript"><!--

function setFocus(){
    var domIFRAME = document.getElementById('theIFRAME'), 
        docIFRAME = domIFRAME ? ( domIFRAME.contentDocument || domIFRAME.contentWindow.document ) : null;
    if( docIFRAME ) docIFRAME.getElementById('toBeSelected').focus(); else console.log("oups!");
}

function handleIframeContent(){
    console.log("okay, it has loaded.");
    document.getElementById('andThen').style.display = 'inline';
}

var domIFRAME = document.getElementById('theIFRAME');
domIFRAME.onload = handleIframeContent;
domIFRAME.src = domIFRAME.getAttribute('data-src');
// --></script>
</body>

Of course, you can do the .focus() bit inside the handleIframeContent(), the demo just wants to give you time to appreciate it is actually not the default state of the page inside the IFRAME.

HTH

flowtron
  • 854
  • 7
  • 20