ON/OFF SWITCH IN APPS SCRIPT GOOGLE SHEET
We'll see here how can we apply on/off switch in apps script project and controll on function to run or stop in one click. Some time we need to stop a function to manage some error or prevent some on from accessing the data. For this purpose we use on/off function and controll on it.
For remembrance of function setting we have used google sheet as a data store. Let's see how we can do it, and controll function in a click.
Let's get started:
STEP ONE-
We have used following code to get this work done. This code has one main function and two subfunctions that proceed and received the respone. This function have put in html file. Some css code also have been used to decorate it.
The code is bellow, copy and paste it into apps script project .
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
input{
width: 40%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
table {
font-family: times;
border-collapse: collapse;
width: 80%;
}
td,th{
border: 1px solid #dddddd;
padding: 8px;
}
</style>
</head>
<body>
<script>
function btf () {
document.getElementById('info').innerHTML = "Working on...";
google.script.run
.withFailureHandler(onFailure)
.withSuccessHandler(onSuccess)
.onoff();}
function onSuccess(resp) {
document.getElementById('bti').value=resp[0];
document.getElementById('info').innerHTML = resp[1];
}
function onFailure(err) {
document.getElementById('bti').value="Click again";
document.getElementById('info').innerHTML = err;
}
</script>
<table cellspacing="0" rules="all" border="1">
<tr>
<th>Status</th>
<td id="info" width="60%"></td>
</tr>
<tr>
<th colspan="2">
<input type="submit"value="Click me" id="bti"onclick="btf();"> <i id="mpwtd"></i>
</th>
</tr>
</table>
</body>
</html>
SECOND STEP-
We have used following apps script code to save and read the data from google sheet.
Make a copy and paste this code into code.gs file. save and pass the permission to run it.
Create a google sheet and get thair id and paste it to red marked place.
Sheet Data Look like this.
Don't know how to get Sheet Id, See following image and copy sheet id.
code.gs
functiondoGet(e) {
return HtmlService
.createHtmlOutputFromFile('index.html')
.setTitle("On/Off switch to run or stop a function");
}
varss = SpreadsheetApp.openById("Sheet Id goes here");
var ws = ss.getSheetByName("onoff");
function onoff (){
var op = ws . getRange ( 2 , 2 ). getValue ();
if(op === "Yes"){
ws.getRange(2, 2).setValue("No");
// set other function to stop
return ['Off','Function is off.'];}
if(op === "No"){
ws.getRange(2, 2).setValue("Yes");
// set other function to run
return ['On','Function is on.'];
}
}
SAVE THE FILE AND CLICK ON DEPLOY BUTTON AND DEPLOY AS WEP APP.
Above code appear as following Result.
I'LL TRY MY LEVEL BEST TO FIX THE PROBLEM.
THANKS FOR VISITING CodyLab
Have a nice day!
-------------------------- -------------------------