Is there a method I can utilize to ensure functionality within Google Apps Script?

I encountered an issue when using innerHTML instead of getBody() and I am looking for assistance with debugging on apps-script as mine is not functioning properly.

 function findText(findme,colour,desc,rule_name) {
  var body = DocumentApp.getActiveDocument().getBody();
  var regExp = case_insensitive(findme);
  var foundElement = body.findText(regExp);
  while (foundElement != null) {
    var foundText = foundElement.getElement().asText();
    var start = foundElement.getStartOffset();
    var end = foundElement.getEndOffsetInclusive();
    foundText.setBackgroundColor(start, end, colour);
    number_oresults++;
    foundElement = body.findText(regExp, foundElement);
    var pusher = '<p><span style="background-color:'+colour+'"><b>'+rule_name+'</b> - '+ desc +'</span></p>';
    results.push(pusher);
   }
} 

Answer №2

There are instances where using active methods in method chaining can result in errors, such as the one indicated in your screenshot (‘can't read property something of null’). For more information, please refer to How does Class Range react when chained with Class Sheet and returns [[]]?

To resolve this issue, consider replacing:

var body = DocumentApp.getActiveDocument().getBody();

with:

var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();

It is important to note that DocumentApp.getActiveDocument() can only be used in bound scripts or standalone scripts executed as add-ons through Run > Test as add-on..., or by publishing the script as a G Suite Editor add-on for Google Documents and running it from the UI.

PLEASE NOTE: The following code works successfully in a standalone script executed under Run > Test as add-on...

function onOpen(e) {
  DocumentApp.getUi()
  .createAddonMenu()
  .addItem('Test 1', 'doSomething1')
  .addItem('Test 2', 'doSomething2')
  .addToUi()
}

function doSomething1(){
  var body = DocumentApp.getActiveDocument().getBody();
  body.appendParagraph('Test 1');
}

function doSomething2(){
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  body.appendParagraph('Test 2');
}

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

Using JavaScript and jQuery, apply a class when a specific radio button is checked and the data attribute meets certain criteria

Need help with changing explanation color based on correct answer selection in multiple choice question. Currently, all choices turn green instead of just the selected correct one. Any assistance is welcome, thank you. html <li class='test-questi ...

Interactive image sliders in a Netflix-inspired style with live previews on hover, fully compatible with Bootstrap framework

I'm looking for suggestions on Twitter Bootstrap compatible jquery plugins that can create a Netflix-style continuously scrolling image carousel with mouse-over functionality. I've tried the carousel included in the Bootstrap JS library, but it r ...

Utilize the Google Drive API to easily upload an Excel file

I'm encountering an issue with the Google Drive API. I've been attempting to upload an Excel file using this API, but haven't had any success. I even tried following the instructions in the Google API documentation without luck. Below is a ...

JavaScript must be able to detect when the checkbox value is reversed, which is dependent on the user-entered data

Hey there, I come across a situation where users are selecting a checkbox to insert or update a row of data in a MySQL database through SparkJava/ Java. The functionality is working fine except for a minor glitch. The issue arises when the checkbox behav ...

Can Bootstrap buttons be manipulated to mimic checkbox behavior effectively?

Looking to implement the data-toggle feature of Bootstrap for enabling users to choose their privilege level. I created a simple demonstration on JSFiddle, where the expected values are: None: 0 User: 1 Administrator: 2 User + Administrator = 3 The iss ...

Encountering an issue while attempting to utilize the .find() method in Mongoose

Currently, I am in the process of setting up a database using MongoDB and integrating the Mongoose ODM with Node.js. After running the code multiple times without any issues, I encountered an unexpected error when adding the last block to utilize the .find ...

Hide the scrollbars on the sidebar

I'm attempting to recreate a sleek scrollbar that caught my eye on the website . To achieve this, I need to have a screen larger than 955px in order to display the sidebar. However, when my sidebar overflows in the y direction, it causes an additional ...

attempting to retrieve the selected values from within an iframe

I'm attempting to access the values of an iframe element select within a dialog on my page. In my JS file, I wrote code to access a select with the ID "firstSelectms2side__sx", but it didn't work as expected. Setting aside the iframe, I also tr ...

What is the process for deselecting text from a text field?

After performing a search and displaying the results on my search form, I've noticed that the text query in the textfield is being marked as selected text even though I don't want it to be. How can I prevent this? Fiddle 1) What is the best app ...

The input tag loses focus after its value is updated using a class method in Angular 8.x

Currently, I am working on integrating a credit card payment method and formatting its number through specific methods. Here is how it is done: HTML <div class="form-group" *ngFor="let formField of cardFields; let cardFieldIndex = index;"> ...

Error: The function subscribe in _store_js__WEBPACK_IMPORTED_MODULE_12__.default is not supported

In my main App component, I am subscribing to the store in a normal manner: class App extends Component { constructor(props) { super(props) this.state = {} this.unsubscribe = store.subscribe(() => { console.log(store.getState()); ...

What is the process of defining a route for a JSON response in an Express application?

I've been following an Angular tutorial on handling form submissions with promises, which I found here. My server is running on Node and I'm using Express to manage routes. However, when I submit the form and reach the line var $promise = $http. ...

Toggle the opening and closing of React components with a map function using onclick

Implementing an onClick function within a map operation, I am encountering an issue where clicking the onClick button changes the state of all items in the map, instead of just the item clicked. This is being done using the useState hook. const [open, se ...

Ensuring nested JSON key existence before rendering in React

When retrieving data from MarvelAPI, there is no certainty that the key being accessed will be available. Therefore, I am implementing if statements to check each key before accessing them. The current code below appears quite messy. Is there a more effic ...

Navigating through different states and managing the URL manually can be a breeze with AngularJS

In my current setup using the meanjs stack boilerplate, I am facing an issue with user authentication. When users log in, their state remains 'logged-in' as long as they navigate within the app starting from the base root URL '/'. This ...

Ways to retrieve the scroll position of content within an iframe

I have a webpage with an iframe that loads another webpage. <iframe id="siteframe" style="width: 400px; height: 400px;" src="http://www.cnn.com"></iframe> I am looking to retrieve the scroll position of the content inside the iframe using Jav ...

When attempting to capture an element screenshot as PNG, a TypeError occurs indicating that the 'bytes' object is not callable

Can someone please help me figure out how to save a screenshot of a specific element in Selenium using Python3? Here is the code I am trying: from selenium import webdriver import pyautogui as pog import time options = webdriver.ChromeOptions() options ...

Incorporate a Web Worker into your webpack library for enhanced performance

I am facing an issue while attempting to include a web worker in my custom npm package. [App] -> [my npm package -> load worker] Within the npm package, I am utilizing worker-loader to import the worker file: import Worker from 'worker-loader! ...

Using NextJS getServerSideProps to Transfer Data to Page Component

Having trouble with my JavaScript/NextJS code, and not being an expert in these technologies. I'm using the method export const getServerSideProps: GetServerSideProps = async () => {} to fetch data from an integrated API within NextJS. The code mig ...

"Can someone guide me on the process of transmitting data to a client using Node in combination with

I am new to web development and struggling to understand how to transfer data from the Node server to the client while also displaying an HTML page. I am aware that res.send() is used to send data, but I'm having difficulty maintaining the client disp ...