Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return focus to spreadsheet

I'm running some Google Scripts linked to buttons on my Google Spreadsheet. After clicking the button to run the script, even though the spreadsheet is still being viewed and the selected cell is still visible, focus on the spreadsheet window is lost. I have to click the window to return focus.

This sounds like a very similar question to the one asked by robodog21. Ed Nelson's solution involving a sidebar with buttons executing the HTML command google.script.host.editor.focus() works well, but I'd really rather not involve a sidebar. I'd prefer to stick with my existing buttons if possible. These are inserted on the spreadsheet as a Google Drawing and then linked to the appropriate Javascript function.

As robodog21 indicated, I am also quite new to Javascript and HTML. I found the following help in Google Apps Script:

Moving browser focus in G Suite

To switch focus in the user's browser from a dialog or sidebar back to the Google Docs, Sheets, or Forms editor, simply call the method google.script.host.editor.focus(). This method is particularly useful in combination with the Document service methods Document.setCursor(position) and Document.setSelection(range).

However I have not figured out how to implement this due to my limited familiarity with HTML.

I have not been able to find a solution in Stack Overflow related specifically to Google Apps Scripts and don't know enough (yet!) to modify other solutions (such as this) to suit my needs. I would appreciate someone clarifying how to apply a solution to my situation.

like image 319
Tim Avatar asked Jan 27 '26 15:01

Tim


1 Answers

After reading Rubén's answer and resigning myself to using a sidebar, I kept playing around with my scripts and realized that all it takes to return focus to the spreadsheet is simply opening and closing a sidebar. The minimum HTML seems to be:

<html>
  <body onload="google.script.host.close()">
  </body>
</html>

This is called in a JS function:

function sidebarCreator() {
  var html = HtmlService.createHtmlOutputFromFile('Page');
  SpreadsheetApp.getUi() 
      .showSidebar(html)
}

I realize this implementation is a little messy in that it pulls up a sidebar which I don't actually want and then immediately closes it. However, it accomplishes what I want with no other changes needed to my existing buttons and functions, so I'm fairly happy. If anyone knows a better method to achieve this result please let me know. Thanks to Rubén for pointing me in the right direction!

like image 185
Tim Avatar answered Jan 29 '26 04:01

Tim



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!