I have 2 Google Apps Script Projects.
- SheetsLib - This is a Library which I created, it contains my go-to functions.
- TestFile - This is a container-bound script, which utilizes the SheetsLib.
SheetsLib contains the following functions which are relevant for this question:
- displayDraftsSelector - Displays the draftSelector Html Page in the Sidebar.
- draftSelector - Html file, which contains a js script as well that calls back-end function to populate a
<select> - getDraftsArr - Server function which returns all gmail drafts from the user.
The SheetsLib function(s) do work, i.e. I have test functions to confirm that. My goal is to enhance this library, so that I can use it in multiple projects with the functionality to allow a user to choose an existing Gmail Draft and send it to selected users (in the active Spreadsheet).
PROBLEM In my new container-bound script, which has access to the Library, I can only show the sidebar but not call a back-end function (which resides in the Library) when I press a button in sidebar:
- I load the view successfully using
displayDraftsSelector()which shows the viewdraftSelector. This is all functionality from the Library. - Then, the view calls the
getDraftsArr()and this is what gets the error. But that function does exist in the Library (and it does work as intended).
The following is the error I see in the console when the sidebar loads:
Uncaught TypeError: google.script.run.withSuccessHandler(...).withFailureHandler(...).getDraftsArr is not a function
What should happen ideally is that, the back-end function getDraftsArr() is called and its result populates the select item. Then the user can select one draft in the sidebar. When the user confirms using a button, the active rows are the recipients. Overall, this all works when I copy-> paste, but what cannot figure out is how to keep the functionality in a library.
The following is the function located in the Library which I am trying to call.
// back-end in Library Project
function getDraftsArr(){
let output = [];
const messages = GmailApp.getDraftMessages();
messages.forEach( message => {
output.push({
id: message.getId(),
subject: message.getSubject()
});
});
return JSON.stringify(output)
}
The following is in the back-end of the library
// front-end in Library Project
<select id="draftsSelect"></select>
<script>
function getDrafts(){
const draftsSelect = document.getElementById("draftsSelect");
google.script.run
.withSuccessHandler( updateDrafts )
.getDraftsArr();
function updateDrafts( drafts ){
var options = "";
var draftsParsed = JSON.parse(drafts);
draftsParsed.forEach( draft => {
options += "<option value='" + draft.id + "'>" + draft.subject + "</option>";
});
draftsSelect.innerHTML = options; }
}
</script>