How to capture change tab event in Google Spreadsh

2020-02-11 12:54发布

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?

2条回答
萌系小妹纸
2楼-- · 2020-02-11 13:45

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>
查看更多
Fickle 薄情
3楼-- · 2020-02-11 13:47

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);
};
查看更多
登录 后发表回答