Chrome extension: Focus input field on main page

javascript html google-chrome google-chrome-extension

298 观看

1回复

644 作者的声誉

I have one HTML page with input box and button. I want to have a chrome extension that can focus on the input element.

HTML page -

<html>
    <body>
        <input type="text" name="box" />
        <button type="button" onclick="clicked()">Click</button>
        <script>
            //document.getElementsByName("box")[0].focus(); <--- this works. But I don't want this.
        </script>
    </body>
</html>

My injected script -

chrome.runtime.onMessage.addListener(function(message, sender, response){
    if(message.action==="start"){
            document.getElementsByName("box")[0].focus(); //<---want this to work. Currently unable to :(
            console.log("started");
    }
});

I get the started log but my element is not focused.

Rest files (i.e. popup.html and popup.js) not shown because they are working fine and irrelevant to this.

I tried simulating mouse click event on the input element (from here) but that method also failed.

Any help regarding this is appreciated. Open to jquery based solutions.

Thanks.

作者: aquaman 的来源 发布者: 2017 年 12 月 27 日

回应 1


0

481 作者的声誉

send message when HTML document is ready.

作者: Pankaj Rupapara 发布者: 2017 年 12 月 29 日
32x32