Search code examples
javascriptgoogle-apps-scriptgoogle-sheetsgoogle-picker

Accessing HTML script variable from google script


I'm trying to put together a picker in google sheets. Once a file has been uploaded to google drive, I want the url to be posted in the current cell in the spreadsheet.

This is my pickerCallback located in an html file:

var message;

function pickerCallback(data) {
    var action = data[google.picker.Response.ACTION];
    if (action == google.picker.Action.PICKED) {
        var doc = data[google.picker.Response.DOCUMENTS][0];
        var id = 'https://drive.google.com/open?id=' + doc[google.picker.Document.ID];

        google.script.run.accessSpreadsheet(); 

    } message = id;
    document.getElementById('result').innerHTML = message;
}

This returns the url in the picker dialog box.

My accessSpreadsheet function looks like this and is located in a google script file:

function accessSpreadsheet() {
     var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
     var currentCell = sheet.getCurrentCell();
     currentCell.setValue(message);
     return spreadsheet;
}

The function runs but it cannot define message. Is there a way to access the variable defined in the function in the html file from the google scripts function? Or is there another better way to do this?


Solution

  • Solution:

    Pass the string id from client side to server.

    Snippets:

    google.script.run.accessSpreadsheet(id); 
    

    function accessSpreadsheet(id) {
    
     currentCell.setValue(id);
    

    Reference:

    Client-Server communication