1

I have 'discovered' the Sidebar functionality in Google Spreadsheet. Very neat.

I have different tabs and the Sidebar acts as a help function. If I select the next step in the Sidebar, I can open the tab that contains the next step.

Now I'm kind of stuck. When the user selects a different tab, I like to populate the Sidebar with corresponding information.

Though I know how to fill the information, I'm looking for the 'trigger' to run the function.

So my question boils down: how do I capture the change tab event?

Stefan van Aalst
  • 788
  • 1
  • 7
  • 19

2 Answers2

3

Use the poller technique demonstrated in How to poll a Google Doc from an add-on. Unlike a time-based trigger, this relies on a client-side delay loop in the sidebar html to make calls to your script on Google's servers.

Here's how you can modify the example from that question.

in Code.gs

  • Add a function to get the current tab name
  • Replace DocumentApp with SpreadsheetApp
  • Optionally, delete all the irrelevant cursor / selection stuff.
/**
 * Gets the name of the current tab
 *
 * @return {string} The selected tab name.
 */
function getActiveTab() {
  return SpreadsheetApp.getActiveSheet().getName();
}

in HTML

  • replace the poll() function with this one.
  • Optionally, delete all the irrelevant cursor / selection stuff.
<div id="tab-name">loading...</div>

...

/**
 * Poll server-side function(s) at the given interval.
 *
 * @param {Number} interval   (optional) Time in ms between polls.
 *                            Default is 2s (2000ms)
 */
function poll(interval){
  interval = interval || 2000;
  setTimeout(function(){
    google.script.run
     .withSuccessHandler(
       function(tabName) {
         // DEMO - just display name of selected tab
         $('#tab-name').text(tabName);
         //Setup the next poll recursively
         poll(interval);
       })
     .withFailureHandler(
       function(msg, element) {
         showError(msg, $('#button-bar'));
         element.disabled = false;
       })
     .getActiveTab();
  }, interval);
};
Community
  • 1
  • 1
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
0

In order to get it to work, I needed to add the following in the beginning of the HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>

<script>
$(function() {
// Start polling for updates
poll(1000);
}); 
</script>
Stefan van Aalst
  • 788
  • 1
  • 7
  • 19
  • That was already in the code from [How to poll a Google Doc from an add-on](http://stackoverflow.com/questions/24773177/how-to-poll-a-google-doc-from-an-add-on), unless you got over-zealous with your code replacement. – Mogsdad Oct 27 '14 at 21:06