Issue with Google Scripts Trigger not activating

I'm having difficulty getting my script to automatically run at around 6AM. I've set up the trigger for this script to run on a "Time-Driven" basis using the "day timer" option between 6-7 am. Despite setting up failure notifications to email me immediately, I'm not receiving any alerts and the script isn't executing as expected. When I manually run the script, it works perfectly fine, but the goal was to automate the process. I'm unsure of what I might be doing wrong in this case. I've tried deleting and re-adding triggers, following examples from others who faced similar issues, but that hasn't resolved the problem for me. Could there be something within my script preventing it from running automatically?

function getMessagesWithLabel() {

 var destArray = new Array();
 var label= GmailApp.getUserLabelByName('Personal/Testing');
 var threads = label.getThreads(0,2);

  for(var n in threads){
        var msg = threads[n].getMessages();
        var body = msg[0].getPlainBody();
        var destArrayRow = new Array();
        destArrayRow.push('thread has '+threads[n].getMessageCount()+' messages');
          for(var m in msg){
                     destArrayRow.push(msg[m].getPlainBody());
           }
  destArray.push(destArrayRow);           
        }
Logger.log(destArray);
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getActiveSheet();
if(ss.getLastRow()==0){sh.getRange(2,1).setValue('getMessagesWithLabel() RESULTS')};
sh.getRange(2,1,destArray.length,destArray[0].length).setValues(destArray);


}

Answer №1

The issue arises from using getActiveSheet which retrieves the sheet currently displayed on the user interface. However, when a time-driven trigger is activated, there may not be a sheet visible on the UI.

To resolve this problem, replace getActiveSheet with getSheetByName, or even better, obtain the sheet by its unique ID (for more information, refer to Get Google Sheet by ID?)

For further details and resources:

Answer №2

It's possible that the issue you're experiencing is due to the absence of an "ActiveSpreadsheet" during a trigger event when the script is not directly linked to the spreadsheet (i.e., when the spreadsheet is closed). In such cases, consider using the following workaround:

var ss = SpreadsheetApp.openById(id); // where 'id' is the unique identifier of the spreadsheet
var sh = ss.getSheetByName(name); // Specify the name of the target sheet e.g., "Sheet1"

Aside from the above, your code appears to be generally correct. However, please note that the function label.getThreads(0,2) limits the number of threads retrieved to 2, which may be intentional on your part.

Additionally, there seems to be a discrepancy in the parameters set for getRange() method. Instead of 2,1, it should probably be 1,1 as shown below:

if(ss.getLastRow()==0){sh.getRange(1,1).setValue('getMessagesWithLabel() RESULTS')};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for efficiently reading a large volume of documents (1M+) from a collection in Cloud Firestore?

Encountering an error of 9 FAILED_PRECONDITION: The requested snapshot version is too old. const ref = db.collection('Collection'); const snapshot = await ref.get(); snapshot.forEach((doc,index) => { ...utilize data }) Want to retrieve all ...

Preserving data in input fields even after a page is refreshed

I've been struggling to keep the user-entered values in the additional input fields intact even after the web page is refreshed. If anyone has any suggestions or solutions, I would greatly appreciate your assistance. Currently, I have managed to retai ...

When "this" doesn't refer to the current object, how to self reference an object

I am currently working on developing a modular series of element handlers for an application that features pages with different configurations. For example, the 'Hex T' configuration includes elements labeled from 'A' to 'O', ...

Transform a section of text into JSON format to utilize in DataTables

Currently, I am utilizing DataTables and Leaflet in my project. The data displayed below needs to be represented on my screen using Datatables. Specifically, I would like to convert it into JSON format without including the {....} part. How should I proc ...

Menu secured in place within the wrapper

My website is contained in a wrapper with a max width, and I have a fixed side menu that can be toggled with a button. The problem I am facing is keeping the fixed side menu within the page wrapper. Fixed elements are typically positioned relative to the ...

Angular 14 presents an issue where the injectable 'PlatformLocation' requires compilation with the JIT compiler; however, the '@angular/compiler' module is currently missing

I've encountered the following error and have tried multiple solutions, but none of them have been successful: Error: The injectable 'PlatformLocation' requires JIT compilation with '@angular/compiler', which is not available. ...

Is it possible to assign two AngularJS modules to a single DOM element simultaneously?

Let's dive into a classic scenario involving portal/CMS widgets: It's uncertain whether or not AngularJS will be present on the page Any number of widgets may or may not exist on the page Each widget could belong to a specific family, with mul ...

Problem with Bootstrap Datepicker click functionality

I am currently utilizing the bootstrap datepicker along with bootstrap-rtl. The problem I encountered was that I had two fields, one for the date and one for the name. The datepicker would not appear until I clicked on the date input first, then on the na ...

Unlock encrypted files without allowing users to access them

Looking to incorporate model-viewer or three.js into my personal website to showcase 3D models. To display these models online, the client must retrieve files from the server (including the 3D mesh and texture images). However, I want to prevent my visito ...

Receiving a 400 Bad Request message when attempting to send JSON data via AJAX post request

Despite reading numerous questions about this problem on stackoverflow, nothing has helped me so far. Here is the function I am struggling with: function ip_login(){ //alert(JSON.stringify(arr_login)); $.ajax({ crossdomain: true, ...

Is there a way to modify the text color of table TD using Javascript?

I have experience with HTML/CSS, for example I can make text turn red using the code <table><tr><td style="color:#f00;">text</td>. However, I am struggling with JavaScript. When I try to change the color of a table cell u ...

C# GridView using a modal popup

Currently, I am working on incorporating a lightbox into a gridview. The lightbox I have chosen to use can be found here on Particle Tree's website Essentially, in order to make the lightbox function correctly, you need to include a css and rel attr ...

The Combo Box Select2 display is not showing correctly

In my web application, I'm dynamically adding new rows to a table using JavaScript. Each row contains an element where data is loaded from the ViewBag, and I also want to apply the Select2 class to this element. Here is the current code snippet: < ...

React: Issue with For Loop not recognizing updates in Hook's State

Recently, I successfully created a React application that displays each word of a sentence at a user-defined time interval for fast reading. However, I am now facing a challenge as I attempt to add a pause button functionality to the app. When I press the ...

Select an image from the browser using JavaScript, adjust its size, and then transmit it to the server. Finally, utilize PHP to properly save the image

I am currently tackling the challenge of implementing a classical feature where users can select a file in their browser ("Browse"), have JavaScript resize it to a maximum width/height of 500 pixels, upload it to the server, and then save it to disk using ...

Utilizing Polymer with iron-ajax for seamless binding of Google Sheets data through JSON

Just starting out with Polymer... I'm attempting to set up a repeater for some HTML using data stored in a Google Sheets document, accessed through its JSON data. Here's the link to the JSON data I've been trying to implement the followin ...

Is my jQuery code generating a large number of DOM objects?

I am currently developing a hex dumper in JavaScript to analyze the byte data of files provided by users. To properly display a preview of the file's data, I am utilizing methods to escape HTML characters as outlined in the highest-rated answer on thi ...

Issue: Headers cannot be set after they have been sent. This is a problem in node.js

I'm trying to create an application that allows users to execute commands via a URL, but I keep encountering this error message: _http_outgoing.js:346 throw new Error('Can\'t set headers after they are sent.'); ^Error: Can't ...

Khan Academy project "Bookshelf" is experiencing an issue where the For Loop is not

"This new program showcases an array of books with the use of a loop, allowing multiple books to be displayed in a row." I am looking to implement the for loop to showcase each book stored in the array. Currently, the 'i' variable rema ...

Making a secure connection using AJAX and PHP to insert a new row into the database

Explaining this process might be a bit tricky, and I'm not sure if you all will be able to assist me, but I'll give it my best shot. Here's the sequence of steps I want the user to follow: User clicks on an image (either 'cowboys&apos ...