- In your situation,
code.gs
and code2.gs
are in a project of a container-bound script type of Google Document.
If my understanding is correct, how about this answer? Please think of this as just one of several answers.
Modification points:
In your script, the scripts of code.gs
and code2.gs
are used as one project at the script editor. So in your script, there are 2 same functions of onOpen()
in the project. In this case, only one of them is run. In your case, onOpen()
of code2.gs
is run and the error of ReferenceError: "A" is not defined.
occurs.
Modified script:
If you want to modify your script and you want to work the functions when the Google Document is opened, how about the following modification?
1. Copy and paste the following script to code.gs
and code2.gs
of the script editor:
code.gs:
var ui = DocumentApp.getUi();
function installedOnOpen () {
A = prompt('Hello'); // or ui.prompt('Hello').getResponseText();
sample(A);
}
code2.gs:
function sample (A) {
if (A === "123") {
ui.alert('Hello')
}
}
Or, if you want to run independently 2 functions, how about the following modification? In this modification, the value is saved using PropertiesService.
code.gs:
var ui = DocumentApp.getUi();
function installedOnOpen () {
A = prompt('Hello'); // or ui.prompt('Hello').getResponseText();
PropertiesService.getScriptProperties().setProperty("key", A);
}
code2.gs:
function sample () {
var A = PropertiesService.getScriptProperties().getProperty("key");
if (A === "123") {
ui.alert('Hello')
}
}
Or, you can also modify as follows. But, in your situation, this might not be required.
function installedOnOpen () {
var ui = DocumentApp.getUi();
var A = ui.prompt('Hello').getResponseText();
if (A === "123") {
ui.alert('Hello');
}
}
2. Install OnOpen event trigger:
In order to run the function of installedOnOpen
when the Google Document is opened, please install the OnOpen event trigger to the funciton of installedOnOpen
as the installable trigger.
3. Run script:
In your case, there are 2 patterns for running script.
Pattern 1:
Open Google Document.
Pattern 2:
Run installedOnOpen
at the script editor.
By above, installedOnOpen
is run. And you can see the dialog at Google Document.
Note:
- This modification supposes that the function of
prompt()
returns the value of 123
as the string value.
- If you cannot provide the script of
prompt()
, as a test case, how about modifying from prompt('Hello');
to ui.prompt('Hello').getResponseText();
?
References:
If I misunderstood your question and this was not the direction you want, I apologize.