Using triggers with custom functions on Google Apps Script - google-apps-script

I had a prob with my script, which was greatly answered in this question.
Basically custom functions cannot call services that require authorization. However, as far as I understood if I use simple triggers, such as onEdit it could work.
I checked the documentation suggested in the previous question, however I wasn't successful applying that to my code, which you can see below:
function FileName (id) {
var ss = DriveApp.getFileById(id);
return ss.getName();
}
How could I adapt my code to use simple triggers?
Here is a sample sheet that replicates the problem.

I believe your goal as follows.
You want to use your function of FileName as the custom function of Google Spreadsheet.
You want to automatically retrieve the filename when the file ID is put to the column "B".
You want to put the filename to the column "C".
Issue and workaround:
Unfortunately, when the custom function is used, in the current specification, the most methods except several methods (for example, one of them is UrlFetchApp.) that the authorization is required cannot be used. By this, DriveApp.getFileById(id) in your script cannot be used with the custom function. But there is a workaround. At the custom function, UrlFetchApp can be used. In this answer, I would like to propose to use the Web Apps with UrlFetchApp as the wrapper for authorizing. By this, the authorization can be done with the Web Apps. So your function can be run by the custom function.
Usage:
1. Prepare script.
Please copy and paste the following script to the script editor and save it.
const key = "samplekey"; // This is a key for using Web Apps. You can freely modify this.
// This is your function.
function FileName_(id) {
var ss = DriveApp.getFileById(id);
return ss.getName();
}
// Web Apps using as the wrapper for authorizing.
function doGet(e) {
let res = "";
if (e.parameter.key === key) {
try {
res = FileName_(e.parameter.id);
} catch (err) {
res = `Error: ${err.message}`;
}
} else {
res = "Key error.";
}
return ContentService.createTextOutput(JSON.stringify({value: res}));
}
function Filename(id) {
const webAppsUrl = "https://script.google.com/macros/s/###/exec"; // Please set the URL of Web Apps after you set the Web Apps.
const res = UrlFetchApp.fetch(`${webAppsUrl}?id=${id}&key=${key}`);
if (res.getResponseCode() != 200) throw new Error(res.getContentText());
return JSON.parse(res.getContentText()).value;
}
2. Deploy Web Apps.
On the script editor, Open a dialog box by "Publish" -> "Deploy as web app".
Select "Me" for "Execute the app as:".
By this, the script is run as the owner.
Select "Anyone, even anonymous" for "Who has access to the app:".
In this case, the access token is not required to request to Web Apps. But in this sample script, a key for requesting to Web Apps is used.
Click "Deploy" button as new "Project version".
Automatically open a dialog box of "Authorization required".
Click "Review Permissions".
Select own account.
Click "Advanced" at "This app isn't verified".
Click "Go to ### project name ###(unsafe)"
Click "Allow" button.
Click "OK".
Copy the URL of Web Apps. It's like https://script.google.com/macros/s/###/exec.
When you modified the Google Apps Script, please redeploy as new version. By this, the modified script is reflected to Web Apps. Please be careful this.
Please set the URL of https://script.google.com/macros/s/###/exec to url of above script. And please redeploy Web Apps. By this, the latest script is reflected to the Web Apps. So please be careful this.
3. Test this workaround.
When the file ID is put to the cell "A1", please put =filename(A1) to a cell as the custom function. By this, the script is run and the response value is returned.
Note:
Above sample script is a simple sample script for testing your script. So when you want to use the various methods, this post might be useful.
Please use this script with enabling V8.
As other method, I think that when the file ID is manually put to the column "B", the installable OnEdit trigger can be used. The sample script is as follows. Please set the sheet name. And please install the trigger to the function of installedOnEdit. Ref By this, when the file ID is put to the column "B" of sheetName, the file ID is put to the column "C".
function installedOnEdit(e) {
const sheetName = "Sheet1";
const range = e.range;
const sheet = range.getSheet();
if (!(sheet.getSheetName() == sheetName && range.getColumn() == 2 && range.getRow() > 1)) return;
const value = range.getValue();
let res = "";
try {
res = DriveApp.getFileById(value).getName();
} catch(e) {
res = e.message;
}
range.offset(0, 1).setValue(res);
}
References:
Web Apps
Taking advantage of Web Apps with Google Apps Script
Enhanced Custom Function for Google Spreadsheet using Web Apps as Wrapper
Related questions
Can you write a Google Sheets function that draws something?
Error when running Youtube Data Service in App Scripts (js) – Daily Limit for Unauthenticated Use Exceeded
How to enable not authorized users to protect the spreadsheet
Changing Owner of the Sheet irrespective of the duplicator
Installable Triggers

As you can draw from the documentation, simple triggers cannot access services that require authorization neither
You have to use installable triggers instead.
However the workflow is very different from custom functions.
In your specific case, you can implement e.g. that when a cell in column A is being edited (that is a new URL is being inserted) - the respective file name is being found and returned into column D.
You can retrieve the value and the row in which the new URL is being inserted with help of event objects.
Sample:
function FileName (event) {
var id = event.value;
var ss = DriveApp.getFileById(id);
var row = event.range.getRow();
var sheet = event.range.getSheet();
// for column D:
var column = 4;
var returnCell = sheet.getRange(row,column);
returnCell.setValue(ss.getName());
}
For using an installable onEdit trigger - bind it to this function through going on Edit > Current project's triggers as explained here.

Related

Access Spreadsheet Cell values from library script

Is there a way I can access data, stored within a spreadsheet-file from the library script?
I want to use 1 Google Apps Script from multiple Google Spreadsheet files within my Google Drive.
I followed this answer: "you could use Libraries. The idea is that you create one script that you use as a library" and could successfully import the library to my project.
In order to work, the scripts within the library need some of the cell-values stored in the google sheet files. I know how to access the script via a helper function in my sheet-bound script file. For example:
function loc_my_credits()
{
SISTRIXAbfrageFreigabe.my_credits();
}
Whilst "SISTRIXAbfrageFreigabe" is the library name, and my_credits a function within the library.
When I call loc_my_credits from sheets, nothing happens. My best guess: the script cant read data from the spreadsheet file it needs to execute.
The my_credits script from the library file looks like this:
function my_credits(){
// Base URL to access customsearch
var urlTemplate = "https://api.sistrix.com/credits?api_key=%KEY%";
// initialize sheets: 1. Get the spreadsheet, 2. Get the first and the second sheets in this spreadsheet
var spreadSheet = SpreadsheetApp.getActiveSpreadsheet();
var inputSheet = spreadSheet.getSheets()[0];
// Script-specific credentials & search engine
var sistrix_Apikey = inputSheet.getRange('A2').getValue();
var url = urlTemplate.replace("%KEY%", encodeURIComponent(sistrix_Apikey));
var params = {
muteHttpExceptions: true
};
var xml = UrlFetchApp.fetch(url).getContentText();
var document = XmlService.parse(xml);
var root = document.getRootElement();
var items = document.getRootElement().getChildren();
for (var i = 0; i < items.length; i++) {
if(items[i].getName() == 'answer'){
var answer = items[i].getChildren();
return answer[0].getAttribute('value').getValue();
}
}
return 0;
}
Is there a way I can access the data stored in the spreadsheet file from the library script?
I'm writing this answer as a community wiki, since the issue was resolved from the comments section, in order to provide a proper response to the question.
The problem was related to the usage of methods that need scopes that require authorization, therefore it would be expected that simple triggers would show the error:
You do not have permission to call SpreadsheetApp.openById
Google's documentation states that installable triggers would solve the problem:
Installable triggers, however, offer more flexibility than simple triggers: they can call services that require authorization
According to s.Panse, the usage of installable triggers has resolved the issue in this case.
References:
google script openById : You do not have permission to perform that action
Installable Triggers

Changing Owner of the Sheet irrespective of the duplicator

I have a spreadsheet which contains a sheet that can be duplicated using a script by various users. The problem is when the user duplicates the sheet he becomes the default owner and gets the rights to edit even the protected ranges for that sheet.
My current script copies the protection to new sheet perfectly but the duplicator user becomes the editor for the same.
Please help me in how can a user who is allowed to duplicate the sheet but does not become editor of the protected ranges or a method to reset the owner of the sheet (not the spreadsheet) back to admin user.
My current code:
function Protect() {
var spreadsheet = SpreadsheetApp.getActive();
var myValue = SpreadsheetApp.getActiveSheet().getSheetName();
spreadsheet.duplicateActiveSheet();
var totalSheets = countSheets(); //script function
myValue = "DO" + totalSheets;
SpreadsheetApp.getActiveSpreadsheet().renameActiveSheet(myValue);
var protection = spreadsheet.getActiveSheet().protect();
protection.setUnprotectedRanges([spreadsheet.getRange('C2:E5'), spreadsheet.getRange('C6:D7'), spreadsheet.getRange('F5:G6'), spreadsheet.getRange('B9:G18'), spreadsheet.getRange('G7:G8')])
.removeEditors(['user1.com', 'user2.com', 'user3.com']);
spreadsheet.getRange('G2').setValue(myValue);
spreadsheet.getRange('G3').setValue(new Date()).setNumberFormat('dd-MMM-YYYY');
spreadsheet.getRange('H1:H').clearContent();
};
I believe your goal as follows.
When the script of Protect() is run by an user who is not the owner, you want to permit to copy the sheet and don't want to add the user as the editor to the copied whole sheet using Google Apps Script.
The Spreadsheet has already been shared with the users.
Modification points:
In this case, I thought that to run the script by the owner might be the solution of your issue, when the user runs the script.
When the user is run the script, in order to run the script by the owner who is not the user, I would like to propose to use Web Apps.
Usage:
1. Prepare script.
Please copy and paste the following script to the script editor and save it.
function doGet() {
script();
return ContentService.createTextOutput();
}
function Protect() {
const url = ScriptApp.getService().getUrl();
UrlFetchApp.fetch(url, {headers: {authorization: "Bearer " + ScriptApp.getOAuthToken()}});
// DriveApp.getFiles() // This is used for automatically detecting the scope of "https://www.googleapis.com/auth/drive.readonly". This scope is used for the access token.
}
// This script is the same with your "Protect".
function script() {
var spreadsheet = SpreadsheetApp.getActive();
var myValue = SpreadsheetApp.getActiveSheet().getSheetName();
spreadsheet.duplicateActiveSheet();
var totalSheets = countSheets(); //script function
myValue = "DO" + totalSheets;
SpreadsheetApp.getActiveSpreadsheet().renameActiveSheet(myValue);
var protection = spreadsheet.getActiveSheet().protect();
protection.setUnprotectedRanges([spreadsheet.getRange('C2:E5'), spreadsheet.getRange('C6:D7'), spreadsheet.getRange('F5:G6'), spreadsheet.getRange('B9:G18'), spreadsheet.getRange('G7:G8')])
.removeEditors(['user1.com', 'user2.com', 'user3.com']);
spreadsheet.getRange('G2').setValue(myValue);
spreadsheet.getRange('G3').setValue(new Date()).setNumberFormat('dd-MMM-YYYY');
spreadsheet.getRange('H1:H').clearContent();
};
In this script, countSheets() is not included. Because I'm not sure about countSheets() from your question. So please be careful this. Please prepare this.
2. Deploy Web Apps.
On the script editor, Open a dialog box by "Publish" -> "Deploy as web app".
Select "Me" for "Execute the app as:".
By this, the script is run as the owner.
Select "Anyone" for "Who has access to the app:".
In this case, the access token is required to request to Web Apps.
Click "Deploy" button as new "Project version".
Automatically open a dialog box of "Authorization required".
Click "Review Permissions".
Select own account.
Click "Advanced" at "This app isn't verified".
Click "Go to ### project name ###(unsafe)"
Click "Allow" button.
Click "OK".
3. Test this workaround.
Please click the button assigned with Protect. By this, the script is run by the owner. By this, even when the user is clicked the button, the result of script is the same with that run by the owner.
Note:
Please use this script with enabling V8.
References:
Web Apps
Taking advantage of Web Apps with Google Apps Script

How do I get permission to send an email using MailApp.sendEmail from my google sheets [duplicate]

I have a problem with some Google Script stuff. Basically, my goal is to have the script check to see if a client's case was resolved and then send an email to them that the issue has been resolved. I've gotten the logic done on when to send an email, but every time I try and implement it into the spreadsheet, I get the error:
Error
You do not have permission to call MailApp.sendEmail. Required permissions: https://www.googleapis.com/auth/script.send_mail (line 8).
I've got a simple function to test the functionality of it, and when run in the script editor it works fine, but not on the spreadsheet. Here is my sample function:
function myFunction(row) {
var sheet = SpreadsheetApp.getActiveSheet();
var rng = sheet.getRange(row, 1, 1, 2);
var ara = rng.getValues();
var email = ara[0][0];
MailApp.sendEmail(email, "TEST", "This is a test of sendEmail().");
return "Email sent.";}
According to the Apps Script Custom Functions documentation:
If your custom function throws the error message You do not have permission to call X service., the service requires user authorization and thus cannot be used in a custom function.
To use a service other than those listed above, create a custom menu that runs an Apps Script function instead of writing a custom function. A function that is triggered from a menu will ask the user for authorization if necessary and can consequently use all Apps Script services.
Method 1
Basically, you can replicate the wanted behavior of the two functions above with this:
function SendEmail() {
var message = "This is your response";
var subject = "You have feed back in the parking lot";
var ss = SpreadsheetApp.getActiveSheet();
var textrange = ss.getRange("F2");
var emailAddress = ss.getRange("B2").getValue();
if (textrange.isBlank() == false)
MailApp.sendEmail(emailAddress, subject, message);
}
And in order to trigger the execution of this function, you can make use of Apps Script triggers and choose one which is the most convenient for your use-case.
Method 2
You can also create a custom menu and with the option of triggering the above function. You only need to add this:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu("My Menu")
.addItem("Send Email", "SendEmail")
.addToUi();
}
And this is how it will look like on the Spreadsheet:
Reference
Apps Script Custom Functions;
Apps Script Range Class - isBlank();
Apps Script Custom Menus;
Apps Script Triggers.
I encountered the same problem today "You do not have permission to call MailApp.sendEmail".
I solved this by doing the next steps:
open "Tools" -> "Script editor"
in "Script editor" click on "View" -> "Show manifest file"
open the "appscript.json" file that appeared in the left section of your screen and add "https://www.googleapis.com/auth/script.send_mail" to the oauthScopes, like this:
{
"oauthScopes": ["https://www.googleapis.com/auth/spreadsheets", "https://www.googleapis.com/auth/script.send_mail"],
}
PS: I assigned the script to an image, which basically acts like a button.

Hide / show specific Sheets tabs for specific users on shared file

My google doc should prompt a login box upon opening the Google Sheets file and, based on the password, it should display a specific tab. E.g. for "password1" it should allow the user to see only tab "Sheet1" and other sheets should be hidden. Similarly, for "password2" it should allow the user to see and work on tab "Sheet2" only.
I tried to run the following code, however it shows some errors.
function showLoginDialog() {
var sheet3 = SpreadsheetApp.getActiveSheet('Sheet3');
sheet3.hideSheet();
var sheet2 = SpreadsheetApp.getActiveSheet('Sheet2');
sheet2.hideSheet();
var sh = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet('Sheet1');
var ui = SpreadsheetApp.getUi();
var prompt = ui.prompt('Password','Enter Password',ui.ButtonSet.OK_CANCEL);
var response = prompt.getResponseText();
var button = prompt.getSelectedButton();
if(button==ui.Button.OK) {
if(response=='pwd3') {
sheet3.activate();
}//end of inner if
if(response=='pwd2'){
sheet2.activate();
}
}//end of main if
}//end of function
The Google Sheets file should ask for the password upon opening it, and it should display the respective sheet based on the password.
You want to open only one of all sheets in the Spreadsheet by the inputted value from the dialog.
For example, when the value of pwd2 is inputted, you want to open only "Sheet2".
You want to open the dialog when the Spreadsheet is opened.
If my understanding is correct, how about this modification? Please think of this as just one of several answers.
The flow of the modified script is as follows.
Open only "Sheet1" as a default, when the Spreadsheet is opened.
Open a dialog.
When pwd2 is inputted, only "Sheet2" is opened.
When pwd3 is inputted, only "Sheet3" is opened.
If you want to open the dialog when the Spreadsheet is opened, please install OnOpen event trigger to RunOnOpen().
How to install OnOpen trigger:
Open the script editor.
Edit -> Current project's triggers.
Click "Add Trigger".
Set RunOnOpen for "Choose which function to run".
Set "From spreadsheet" for "Select event source".
Set "On open" for "Select event type".
Modified script:
function RunOnOpen() {
// Updated
var openSheet = function(ss, sheets, sheet) {
var s = ss.getSheetByName(sheet);
s.showSheet();
ss.setActiveSheet(s);
for (var i = 0; i < sheets.length; i++) {
if (sheets[i].getSheetName() != sheet) {
sheets[i].hideSheet();
}
}
};
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
openSheet(ss, sheets, "Sheet1"); // Open only "Sheet1" when this function is run.
var ui = SpreadsheetApp.getUi();
var prompt = ui.prompt('Password','Enter Password',ui.ButtonSet.OK_CANCEL);
var response = prompt.getResponseText();
var button = prompt.getSelectedButton();
if (button == ui.Button.OK) {
var sheet = "";
if(response == 'pwd3') {
openSheet(ss, sheets, "Sheet3");
} else if(response == 'pwd2') {
openSheet(ss, sheets, "Sheet2");
}
}
}
Note:
In this modified script, when RunOnOpen() is manually run at the script editor, the script works. In order to do this, I didn't use the event object of OnOpen event trigger.
References:
hideSheet()
showSheet()
Installable Triggers
If I misunderstood your question and this was not the result you want, I apologize.
Updated:
When I tested several times for this script, there are the case that "Sheet1" sheet and another sheet are opened. In order to avoid this situation, I updated the script. Could you please confirm above script again?
Edit:
You want to make users use the specific sheet of Spreadsheet by inputting each password.
You don't want to publish the script for users.
You want to make several users use the Spreadsheet, simlutaneously.
If my understanding for your goal is correct, how about this workaround?
Create each Spreadsheet for each user.
By this, the simultaneous access for the Spreadsheet can be achieved.
Use Web Apps in order to open each Spreadsheet by inputting the password.
The flow of this workaround is as follows.
An user, who logged in Google, open Web Apps.
The user input the password and click "OK".
Checking the password at the server side and return the URL of Spreadsheet corresponding to the password.
Open the Spreadsheet from the URL.
By this flow, I think that top 3 aims can be achieved.
Sample script:
Before you use this script, please split the Spreadsheet for each sheet, and retrieve each URL of Spreadsheet.
When you use this, please deploy Web Apps with the following condition. If you want to know how to deploy Web Apps, please check this.
Execute the app as: Me.
Who has access to the app: Anyone
By this condition, users are required to log in to Google for accessing to Web Apps.
Users accesses to the URL of Web Apps.
Google Apps Script: Code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile("index");
}
function selectSpreadsheet(value) {
var url = "";
if (value == "pwd2") {
url = "### URL of Spreadsheet for password of pwd2 ###";
} else if (value == "pwd3") {
url = "### URL of Spreadsheet for password of pwd3 ###";
}
return url;
}
HTML & Javascript: index.html
<input type="text" id="value" >
<input type="button" value="ok" onclick="openSpreadsheet()">
<script>
function openSpreadsheet() {
var value = document.getElementById("value").value;
google.script.run.withSuccessHandler((url) => {
if (url) window.open(url,'_top');
}).selectSpreadsheet(value);
}
</script>
Note:
When you modified the script, please deploy the project as new version. By this, the latest script is reflected to Web Apps. Please be careful this.
I think that when the each Spreadsheet is shared for only each user, the security will be high.
The maximum number of the simultaneous access for Web Apps is 30. Ref
This is a simple sample script. So if you use this, please modify it for your situation.
From TheMaster's somment, Although it's highly unlikely that users are able to retrieve the passwords from source code, I recommend using private functions and/or properties service for storing of passwords for a extra layer of security.
As a sample, you can use like below by saving the passwords and URLs to PropertiesService.
function selectSpreadsheet(value) {
return PropertiesService.getUserProperties().getProperty(value);
}
References:
Class google.script.run
Web Apps
Taking advantage of Web Apps with Google Apps Script
I don't think this is secure for the following reasons:
Sheets' hidden/visible property is global and not restricted to a single user. If user1 and user2 login one after another at almost the same time, user1's sheet is visible after user1's login; As soon as user2 logs in, user1's sheet will be hidden for both users and user2's sheet will be visible to both user1 and user2
It's easy to unhide sheets. user1 can unhide user2's sheet at any time he wishes to, provided he has edit access to the spreadsheet(which is needed, if you want to display the login dialog).

How do I determine what caused my script to run?

Whenever I attempt to display a UI dialog (e.g. msgBox or alert) it works fine when invoked via a menu item (e.g. from Google Sheets), but it hangs my script if I try to invoke it from the Google Apps Script editor (e.g. via Run > Run function).
My guess is it's because the Google Apps Script editor can't display any UI. To resolve this, I'd like to create a wrapper function that checks how the script was run, and not present UI depending on the source.
The "Executions" screen has the notion of Type (Editor, Standalone, Trigger):
This makes me think there is a way to get this type in code somehow.
Psuedo code of what the function might look like:
function showMessage(message) {
var scriptSource = ???;
if (scriptSource === "Standalone") {
Browser.msgBox(message);
} else {
console.log(message);
}
}
How would I get the scriptSource?
The closest thing I can find is TriggerSource, but that is missing the enum values 'Editor' and 'Trigger'. Furthermore, it's a property only available on a Trigger. I don't know how to access the current trigger. From my understanding, that's only available via the event object (e.g. via triggerUid) on functions acting as triggers. This method I'm running in the apps script editor doesn't have access to an event object.
Not the best solution, but my current workaround is to create 3 versions of each function, and append how it was invoked to the name.
For example, if there was a "Hello World" function:
function onOpen() {
var menu = [
{name: 'Hello World', functionName: 'helloWorldViaMenu_'},
];
SpreadsheetApp.getActive().addMenu('Custom', menu);
}
function helloWorldViaMenu_() {
helloWorld_(false);
}
function helloWorldViaEditor() {
helloWorld_(true);
}
function helloWorld_(invokedFromEditor) {
if (invokedFromEditor) {
Logger.log("Hello world");
} else {
Browser.msgBox("Hello world");
}
}
helloWorldViaEditor is the only that doesn't have a _ at the end so it can be selected via the "Select function" Editor UI dropdown.
You want to know whether the current project is the container-bound script type or the standalone script type.
You want to use Browser.msgBox().
I could understand about your question as above. In order to achieve it, as a workaround,I would like to propose to use Apps Script API. The flow of sample script is as follows. I think that there are several workarounds for your situation. So please think of this as one of them.
Retrieve the parent ID of the project using the method of projects.get in Apps Script API. The parent ID means that the file ID of Google Docs.
When the parent ID is returned, it is found that the project is the container-bound script type.
When the parent ID is NOT returned, it is found that the project is the standalone script type.
When the mimeType of parent ID is Google Form, Browser.msgBox() cannot be used. So the if statement is used for this.
Sample script:
This is a sample script. In this sample script, the script ID of current project is used. Of course, you can also manually give the script ID.
var id = ScriptApp.getScriptId(); // Retrieve scriptId of current project.
var url = "https://script.googleapis.com/v1/projects/" + id + "?fields=parentId";
var res = UrlFetchApp.fetch(url, {headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()}});
res = JSON.parse(res.getContentText());
if ("parentId" in res) {
Logger.log("Container-bound script type.")
var mimeType = DriveApp.getFileById(res.parentId).getMimeType();
if (mimeType === MimeType.GOOGLE_FORMS) {
Logger.log("Browser.msgBox() cannot be used at Google Form.");
} else {
Browser.msgBox("Hello world");
}
} else {
Logger.log("Standalone script type.")
Logger.log("Hello world");
}
Note:
When you use this script, please do the following flow.
Enable Apps Script API at API console.
At least, add the following scopes to the manifests.
https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/script.external_request
https://www.googleapis.com/auth/script.projects.readonly
If in your script, other scopes are required to be added, please add them. And if you want to use the automatically installer of scopes with the script editor, you can achieve it using a library. You can see the detail information at here.
References:
Apps Script API
Manifests
projects.get
Taking Advantage of Manifests by GAS Library
If I misunderstand your question, I'm sorry.
Edit:
You want to confirm whether the function is called from the script editor or the custom menu.
If my understanding is correct, how about this sample script? This is a sample script. The process list can be retrieved by giving the script ID and function name. In this sample script, using "ProcessType" of processes.listScriptProcesses in Apps Script API, it confirms whether the function is called from the script editor or the custom menu.
Sample script:
This is a sample script. The process list can be retrieved by giving the script ID and function name.
When you use this script, please enable Apps Script API at API console, and add a scope of https://www.googleapis.com/auth/script.processes to the manifests.
The how to use this script is as follows.
Run addCustomMenu().
Run sampleFunction at the custom menu.
By this, Call from custom menu is shown in log.
Run sampleFunction at the script editor.
By this, Call from script editor is shown in log.
Script:
function addCustomMenu() {
SpreadsheetApp.getUi().createMenu('sampleCustomMenu').addItem('sample', 'sampleFunction').addToUi();
}
function sampleFunction() {
var scriptId = ScriptApp.getScriptId();
var functionName = "sampleFunction";
var url = "https://script.googleapis.com/v1/processes:listScriptProcesses?scriptId=" + scriptId + "&scriptProcessFilter.functionName=" + functionName;
var res = UrlFetchApp.fetch(url, {headers: {Authorization: "Bearer " + ScriptApp.getOAuthToken()}, muteHttpExceptions: true});
res = JSON.parse(res);
if (!("processType" in res.processes[0])) {
Logger.log("Call from custom menu")
} else if (res.processes[0].processType == "EDITOR") {
Logger.log("Call from script editor")
}
}
References:
Apps Script API
Manifests
processes.listScriptProcesses
ProcessType
Making Dialogs
You can run them from the menu or the script editor. They work the same.
function makeAmenu(){
SpreadsheetApp.getUi().createMenu('A Menu')
.addItem('Run my Dialogs', 'showMyDialogs')
.addToUi();
}
function showMyDialogs(){
var ui=SpreadsheetApp.getUi();
ui.alert('This is an alert');
ui.prompt('This is a prompt');
var html=HtmlService.createHtmlOutput('<p>This is a modeless dialog</p><input type="button" value="Close" onClick="google.script.host.close();" />');
ui.showModelessDialog(html, 'Dialog');
}
If you run a script from here:
The you have to go here to see it: