问题
I made a simple Chrome extension - search with a form.
When I open the extension, there is no default focus on form, but it requires additional click.
Focus is suppose to happen on popup.html form.
Now JavaScript .focus()
method didn't work, Is there any other way to set default focus for Chrome extensions?
HTML:
<input type="text" id="mydata" />
JS:
document.getElementById('mydata').focus();
回答1:
Try something like this:
<html>
<head>
<script type="text/javascript">
function setFocus()
{
document.getElementById("target").focus();
}
</script>
</head>
<body onload="setFocus()">
<input type="text" id="target" name="target" size="25" value="" />
</body>
</html>
it works for me.
回答2:
the latest chrome has supported tabindex
attribute. So you can use
<input type="text" id="mydata" tabindex="1" />
to make it work without any js codes. just FYI.
回答3:
The issue with chrome extensions is that the entire popup.html document has no focus by default. Therefore it's simply not enough to set the focus on an element. You first need to reload the page.
Just put the following code into the page header:
<script type="text/javascript">
function Init () {
if (document.hasFocus)
setInterval ("checkFocus ()", 300);
}
function checkFocus () {
if (!document.hasFocus ()) {
document.location.reload();
}
}
document.getElementById('mydata').focus();
</script>
Then call the code in your body tag:
<body onload="Init ();">
That's it. Please keep in mind that this solution is just a work-around. May future chrome versions fix the focus issue in extensions to make this workaround superfluous.
回答4:
function setFocus(loc) {
window.open(loc, 'popup1', 'height=655,width=710,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=no,minimizable=no').close();
window.open(loc, 'popup1', 'height=655,width=710,status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=no,minimizable=no').status.fixed();
}
Then:
lnkSongTitle.Attributes.Add("onclick", "javascript:setFocus('url')");
or in html onClick
call SetFocus() function
回答5:
Chrome supports autofocus which doesn't require any JavaScript.
<input type="text" id="mydata" autofocus />
来源:https://stackoverflow.com/questions/6594064/auto-focus-in-google-chrome-extension