Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't set focus to input in chrome extension

For some reason I can't set focus on a texbox I have in my popup.html. Here's what I've tried so far:

popup.html:

<input type="text" id="textbox" name="aName" value="" placeholder="blah" />

popup.js:

//Attempt 1
$(function() {      
    $('#textbox').focus();
});

//Attempt 2
setTimeout(function() { $('#textbox').focus(); }, 1000);

I also tried without javascript, using just the autofocus property:

<input type="text" id="textbox" name="aName" value="" placeholder="blah" autofocus />

But none of this worked... Any ideas?

Notes:

  • popup.js is being called, if I put console.log() I get the output
  • The popup is fired by an icon we have next to the omnibar (default_icon)
like image 569
epzee Avatar asked Oct 20 '25 05:10

epzee


2 Answers

This code works with me, try it, it's a workaround

<!DOCTYPE >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Sample Extens</title>
</head>
<body style="padding: 0px; margin: 0px;" >
    <script type="text/javascript" language="javascript">
        if (location.search !== "?foo") {
            location.search = "?foo";
            throw new Error;  // load everything on the next page;
            // stop execution on this page
        }
    </script>

    <div id="Def">
        <input type="text" id="textbox" name="aName" value="" placeholder="blah" />
        <script type="text/javascript" language="javascript">
            document.getElementById("textbox").focus();
        </script>
    </div>
</body>
</html>

enter image description here

like image 59
Tarek El-Mallah Avatar answered Oct 21 '25 18:10

Tarek El-Mallah


I had this same problem. I believe I was able to get it to work by setting an explicit tabindex on the input like tabindex=1

Please give that a try and let me know if it works.

Update

I have a very simple example that works for me. I am using Chrome 19 on Linux.

manifest.js

{
"name": "Auto 'focus'",
    "version": "1.0",
    "manifest_version": 2,
    "description": "An extension to test setting focus",
    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html"
    }
}

popup.html

<!doctype html>
<html>
  <head>
  </head>
  <body>
    <a href="#">Link</a>
    <input type="text" id="foo" tabindex="1" />
  </body>
</html>

Without the tabindex="1" the focus is initially on the Link. With tabindex="1" the focus is on the input element

like image 22
jcbwlkr Avatar answered Oct 21 '25 19:10

jcbwlkr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!