kusi
kusi

Reputation: 187

autofocus attribute ignored on HTML page served by google script

The following google script creates a small website (copied from https://developers.google.com/apps-script/guides/html/templates)

function doGet() {
  return HtmlService
      .createTemplateFromFile('index.html')
      .evaluate();
}

The corresponding index.html (copied from https://www.w3schools.com/tags/att_button_autofocus.asp)

<!DOCTYPE html>
<html>
<body>

<button type="button" autofocus onclick="alert('Hello world!')">Click Me!</button>

<p><strong>Note:</strong> The autofocus attribute of the button tag is not supported in IE 9 and earlier versions.</p>

</body>
</html>

When I load the website, I expect the button to be focused and show "Hello world" on pressing ENTER. However the button is not focused and I need to click the button with the mouse. What do I need to change to make the autofocus attribute to work?

Sample website

PS: This used to work about a year ago

Upvotes: 2

Views: 939

Answers (1)

Tanaike
Tanaike

Reputation: 201553

I confirmed that when autofocus was used, an error of Blocked autofocusing on a form control in a cross-origin subframe. occurred. It was found that by this, the button cannot be focused. Unfortunately, I couldn't find the method for using autofocus for this situation. So in order to avoid this issue, how about this workaround? Please think of this as just one of several answers.

In this workaround, focus() is used.

Modified HTML:

<!DOCTYPE html>
<html>
<body>

<button type="button" id="button" onclick="alert('Hello world!')">Click Me!</button> <!-- Modified -->

<p><strong>Note:</strong> The autofocus attribute of the button tag is not supported in IE 9 and earlier versions.</p>

<script>
  document.getElementById('button').focus(); // Added
</script>
</body>
</html>

References:

If this was not the direction you want, I apologize.

Upvotes: 2

Related Questions