Chaitanya Chandurkar
Chaitanya Chandurkar

Reputation: 2187

SpreadsheetApp.getActiveSpreadsheet() is breaking script

I'm writing my 1st google app script. Spreadsheet opens a sidebar in onOpen(). Sidebar has Button and in SidebarJavaScript.html I have listener to that button. I'm calling SpreadsheetApp.getActiveSpreadsheet() inside listener and after this line script is not executing.

What could possibly be wrong here?

function onScrapeClick(){

    // Disable Button
    this.disabled = true;

    // Get Spreadsheet
    var sheet = SpreadsheetApp.getActiveSpreadsheet();
    this.innerHTML ="Clicked";
    var data = sheet.getDataRange().getValues();

}

Button is getting disabled as for line this.disabled = true; as expected so lister is working properly for sure.

Upvotes: 0

Views: 866

Answers (2)

Daniel Möller
Daniel Möller

Reputation: 86600

You must define the method to get data in a .gs file and call it with google.script.run.

In some Code.gs file:

function getSheetData()
{
   var sheet = SpreadsheetApp.getActiveSpreadsheet();
   var data = sheet.getDataRange().getValues();
   return data;       
}

And in the html script:

function onScrapeClick(){

  // Disable Button
  this.disabled = true;

  // Get Spreadsheet

  this.innerHTML ="Clicked";
  google.script.run
    .withSuccessHandler(
      function(data, element) {
        // code to execute if data was gotten ok
        // the received data is in data argument
      })
    .withFailureHandler(
      function(msg, element) {
        // code to execute if data was not gotten ok
      })
    .getSheetData();

}

Upvotes: 1

Dan Oswalt
Dan Oswalt

Reputation: 2189

getValues is a method of the sheet class, you just need to define the active sheet

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();

Upvotes: 0

Related Questions