2

How to detect and trigger custom action during opening specific sheet in spreadsheet?

I could not find proper function in https://developers.google.com/apps-script/guides/triggers/events

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Michal_Szulc
  • 4,097
  • 6
  • 32
  • 59
  • The tags you chose are not appropriate for this question. Please review [What are tags, and how should I use them?](//stackoverflow.com/help/tagging) – Mogsdad Jun 08 '16 at 20:19
  • Related [How do I make a Sidebar display values from cells?](https://stackoverflow.com/q/30628894/1595451) – Rubén May 16 '19 at 13:20

2 Answers2

3

To do polling as Mogsdad suggested you could use this code in your Sidebar (or any UI element)

$(function() {
   /**
   * On document load, assign click handlers to each button and try to load the
   * user's origin and destination language preferences if previously set.
   */
   poll();
}

function poll(interval){
    interval = interval || 2000;
    setTimeout(function(){
    google.script.run.withSuccessHandler(loadSheetName)
        .withFailureHandler(showError).getSheetName();
    poll();
    }, interval);
};

function loadSheetName(sheetName) {
   alert(sheetName);
   }

function getSheetName() {
   google.script.run.withSuccessHandler(loadSheetName)
        .withFailureHandler(showError).getSheetName();
   }

And in your .gs code

function getSheetName() {
var sheetName =         SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
return sheetName;
}
Rafał Pydyniak
  • 539
  • 4
  • 11
  • This is awesome and was giving me a hint of what i am exactly was looking for. However. it has some syntax errors in it, therefor here my corrected code from above: `$(function(){ poll(); }); function poll(interval){ interval = interval || 2000; setTimeout(function(){ google.script.run .withSuccessHandler(loadSheetName) .withFailureHandler(showError) .getSheetName(); poll(); }, interval); }; function loadSheetName(sheetName) { alert(sheetName); } function showError(error) { alert(error); }` – LJay Mar 11 '19 at 22:16
  • @LJay this code was working back in 2016. If there were changes since there, please append the current answer with your code or add a separate answer with current api calls – Michal_Szulc Feb 19 '20 at 12:35
2

There is no API provided to trigger on user events, aside from the ones in the documentation you've linked.

I can think of only one work-around: If your application involves having a custom UI element, specifically a sidebar or dialog, then you could poll for the active cell, and determine the active sheet from that.

See How to poll a Google Doc from an add-on for a start.

Community
  • 1
  • 1
Mogsdad
  • 44,709
  • 21
  • 151
  • 275