Skip to content Skip to sidebar Skip to footer

Togglebutton For Google Htmlservice

What is the easiest way to get some kind of toggle switch for Google HtmlService? Google UiApp used to be able to create a simple ToggleButton like the following: var toggleButton

Solution 1:

Here's a toggle function that presents a dialog that has a button that turns a light on and off:

function launchLightToggleDialog() {
  let html='';
  html += '<html><head></head><body>';
  html += '<br /><imgid="light"src="" />';
  html += '<br /><inputtype="button"id="btn"value="Toggle"onclick="toggle()" />&nbsp;&nbsp;<labelid="lbl"for="btn"></label>';
  html += '<script>';
  html += 'var light="on";'  
  html += 'var lighton = <?= getMyDataURI(gobj.globals.lightonid) ?>;\n';
  html += 'var lightoff = <?= getMyDataURI(gobj.globals.lightoffid) ?>;\n';
  html += 'window.onload=function(){document.getElementById("light").src=(light=="on")?lighton:lightoff;document.getElementById("lbl").innerHTML=light;}\n';

  html += 'function toggle(){light = (light=="on")?"off":"on";document.getElementById("light").src=(light=="on")?lighton:lightoff;document.getElementById("lbl").innerHTML=light;}\n';
  html += 'console.log("mycode");\n'
  html += '</script>';
  html += '</body></html>';
  let t=HtmlService.createTemplate(html);
  let o=t.evaluate();//The dataURI's get loaded here
  SpreadsheetApp.getUi().showModelessDialog(o,"Light Toggle");
}

The below function just opens up the files where I store the dataURI's of the lighton and lightoff images and it returns the dataURI's as strings for use in the webapp. Making it possible for me to serve the images off of my Google Drive.

functiongetMyDataURI(fileId) {
  const file=DriveApp.getFileById(fileId);
  return file.getBlob().getDataAsString();
}

Demo:

enter image description here

Both functions are Google Apps Script and all JavaScript functions are imbedded in the html string.

If you wish to convert an image to a dataURI:

functionconvImageUrl(url){
  var url=url || "default url";
  var blob=UrlFetchApp.fetch(url).getBlob();
  var b64Url='data:' + blob.getContentType() + ';base64,' + Utilities.base64Encode(blob.getBytes());
  return b64Url;
}

functionsaveDataURIInFile(filename,datauri,type) {
  Logger.log('filename: %s\ndatauri: %s\ntype: %s\n',filename,datauri,type);
  if(filename && datauri && type) {
    var folder=DriveApp.getFolderById(getGlobal('MediaFolderId'));
    var files=folder.getFilesByName(filename);
    while(files.hasNext()) {
      files.next().setTrashed(true);
    }
    var f=folder.createFile(filename,datauri,MimeType.PLAIN_TEXT);
    return {name:f.getName(),id:f.getId(),type:type,uri:DriveApp.getFileById(f.getId()).getBlob().getDataAsString()};
  }else{
    throw('Invalid input in saveDataURIInFile.');
  }
}

Post a Comment for "Togglebutton For Google Htmlservice"