Convert JavaScript code to Google Appscript

Looking for guidance on incorporating Javascript code into my Google Appscript. Here is the code snippet: I have a separate Stylesheet.html file saved. Can someone advise me on how to invoke the functions within the html file?

<script>
  //google.script.run.updateColors();
  
  
  document.querySelectorAll("input[type='number'], input[type='range']").forEach(doStuff);
  
  function doStuff(){
    google.script.run.withSuccessHandler( {
    this.addEventListener("input", function() {
    if (this.type === "range") {
      this.nextElementSibling.value = this.value;
    } else if (this.type === "number") {
      this.previousElementSibling.value = this.value;
    }

  }
    }).updateColors();


  }

  

  
  function updateColors() {
 
  google.script.run.withSuccessHandler({ 
     const colorFront = [ 
    document.querySelector("#color-1-r").value,
    document.querySelector("#color-1-g").value,
    document.querySelector("#color-1-b").value
  ];
  const colorBack = [
    document.querySelector("#color-2-r").value,
    document.querySelector("#color-2-g").value,
    document.querySelector("#color-2-b").value
  ];
  } ).updateDemoColors(colorFront, colorBack).updateBoxesColors(colorFront, colorBack).updateHex(colorFront,colorBack);
  
  }

  function updateHex(colorFront, colorBack) {
    google.script.run.withSuccessHandler(  {
  const colorFrontHex = colorFront.map(function(el) { return Number(el).toString(16).padStart(2, "0").toUpperCase(); });
  const colorBackHex = colorBack.map(function(el) { return Number(el).toString(16).padStart(2, "0").toUpperCase(); });
  document.querySelector("#color-1-hex").value = `#${colorFrontHex.join('')}`;
  document.querySelector("#color-2-hex").value = `#${colorBackHex.join('')}`
  }); 
    
  }

  function updateBoxesColors(colorFront, colorBack) {

    google.script.run.withSuccessHandler(ratio => {
    const ratio = contrast(colorFront, colorBack);
    document.querySelector("#aa-normal").className  = ratio < 0.22222 ? "" : "fail";
    document.querySelector("#aa-large").className   = ratio < 0.33333 ? "" : "fail";
    document.querySelector("#aaa-normal").className = ratio < 0.14285 ? "" : "fail";
    document.querySelector("#aaa-large").className  = ratio < 0.22222 ? "" : "fail";

    const totalWrong = document.querySelectorAll(".fail").length;
    let mouth = document.querySelector("#mouth");
    let smile = document.querySelector("#smile");

    switch(totalWrong) {
      case 0:
        mouth.setAttribute("d", "M 106,132 C 113,127 125,128 125,132 125,128 137,12...
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <?!= include('Stylesheet'); ?>
  </head>
  <body>
    
    <section id="color-contrast">
  <h1>Google Color Contrast Checker</h1>
  <div class="character">
    <div id="jill">
    <svg width="250" height="250" viewBox="0 0 250 250" xmlns="http://www.w3.org/2000/svg" role="img" aria-labelledby="title  desc">
    <title id="title">Contrast Checker</title>
    <desc id="desc">Cartoon of a Caucasian woman smiling, and wearing black glasses and a purple shirt with white collar.</desc>
    <defs>
      <clipPath id="scene">
        <circle cx="125" cy="125" r="115"/>
...      

Seeking advice on integrating Javascript code into Google Appscript. I have a separate Stylesheet.html file saved and need help with invoking the functions within it.

If anyone has suggestions on modifying this for Google Appscript, I'd greatly appreciate it.

Answer №1

Summary

If you need to execute an Apps Script function from your HTML file, you must utilize the google.script.run client-side JavaScript API call.

To invoke the contrast function located in Code.gs, you should include the following code in your Page.html file:

<script>
    google.script.run.contrast();
</script>

Explanation

It is important to note that functions on the client side (like Code.gs in this scenario) must adhere to Apps Script conventions - meaning, it is not possible to access DOM elements, such as document.

If you wish to keep using your existing functions, you will need to integrate them into your HTML file and restrict the Apps Script code to only calling the doGet function.

Resource

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

Issues with AJAX not being triggered upon clicking as expected

I've been delving into AJAX for about 2 hours now, trying to understand how to make it work. It seems like the function is being called, as an alert works perfectly fine. When I tried a different method, it seemed to trigger the function automaticall ...

The Jquery click event refuses to trigger

Below is the JavaScript code that is not functioning: $('#change-priority-modal').find('.btn-primary').unbind().on("click", function () { //my_func_body } Interestingly, the code works perfectly fine in the developer console. I would ...

Can a gulpfile be written in ES6 syntax?

Question: Is there a way to write my gulp file in ES6 to utilize import instead of require, and use => syntax in place of function()? I have the option to use io.js or any version of node.js. gulpfile.js: import gulp from "./node_modules/gulp/index.j ...

``Error: GraphQL server unable to initiate due to a failure in the module.exports

While learning GraphQL, I encountered an error when attempting to start a server. const graphql = require('graphql'); const _ = require('lodash'); const { GraphQLObjectType, GraphQLString, GraphQLInt, GraphQLSchema } ...

What is the best way to manage a session using JavaScript?

Currently developing a website that initially hides all elements except for the password box upon loading. Once the user enters the correct password, all webpage elements are revealed. Seeking a solution to keep the elements visible on reload by utilizing ...

Is the order of elements in a CSS file important?

In my situation, I am dealing with a nested list and enclosing div that was created by Drupal's menu system, so I am unable to modify it. My goal is to replicate the menu from a hardcoded website (link removed). How can I include the sub-items (ul l ...

I'm unable to resolve the issue regarding the message "Property or method is not defined on the instance but referenced during render."

I have a good grasp on what the issue is (the inputs I'm trying to v-model aren't declared), but for some reason, I can't resolve it (or figure out how to) even after studying other posts with the same problem. After comparing my code with ...

Tips for incorporating a set offset while utilizing the scrollTop() function

I have successfully implemented a code that sets a position:fixed to a div when it scrolls past the top of the screen. The code I used is as follows: var $window = $(window), $stickyEl = $('#the-sticky-div'), elTop = $stickyEl.o ...

endless cycle of scrolling for div tags

My goal is to incorporate a tweet scroller on I believe it uses the tweet-scroller from Unfortunately, this link seems broken as the demo is not functioning. I searched for an alternative solution and came across http://jsfiddle.net/doktormolle/4c5tt/ ...

Alert: It is invalid for an <a> element to be nested inside another <a> element according to validateDOMNesting

I've been experimenting with using react-router in conjunction with reactstrap and create-react-app. While setting up the routing within my application, I encountered a need to utilize state for the reactstrap components. To achieve this, I converted ...

"Encountering a problem with compression in Kafka while using the Node.js client with

I am currently utilizing the kafka-node library to consume data from Kafka. It appears that the data I am receiving is compressed with SNAPPY. How can I decompress this data once it has been retrieved? I attempted to use the node-snappy library for decompr ...

Can someone help with the issue where the CSS field position changes when the "X" icon appears, as mentioned in the title? I am looking for a solution to fix this problem

When trying to add an additional field on a page, the "X" icon appears inline with the field and causes the other fields to adjust their position. However, I want the new field to remain in the same position as the title. How can I achieve this while keepi ...

Creating an array of objects by parsing JSON using the jQuery .each() method

I am attempting to generate an array of objects by parsing a JSON file. Here is the pertinent code: //president object constructor function president(a_presName, a_presDates, a_presNick, a_presImage) { this.presName=a_presName; this.presDates=a_pr ...

How to modify values in a JSON array using JavaScript

Currently, I am facing an issue with displaying dates properly on the x-axis of a graph created using Highcharts. To solve this problem, I need to parse the dates from the JSON response. Despite my attempts to manipulate the JSON date, I have not been able ...

Tips on adjusting the dimensions of a switch in kendo UI angular with CSS

Currently, I am utilizing angular in combination with Kendo ui. Is there a way to modify the dimensions of the switch button in Kendo UI Angular using CSS? ...

Integrate HTML code into a preexisting div container

After receiving the HTML from Django views <script> //The code below is within the ready function $("#data").html("{{dict.html}}"); </script> <div id="data" name="data" style="display:block;"></div> The following H ...

Error encountered when attempting to pass a custom component as a prop in VueJS that is undefined

Can you please clarify why Vue is indicating that Unknown custom element: <MyComponent> - did you register the component correctly? is an issue in this code snippet: const CustomComponent = Vue.component('CustomComponent', { template: &a ...

Arrange a series by the actual pixel width of the string

Imagine you have an array of tags represented as strings and you need to display them in a narrow view. Some tags are smaller, allowing for 2 to fit on one line, while larger tags require their own line. Your goal is to sort the array so that the smalles ...

Changing the Month Label Format from Short (MMM) to Long (MMMM) in Angular Material Datepicker

I am looking to customize the month labels in Angular Material datepicker. By default, the month view displays in MMM format and I want to change it to MMMM using custom MatDateFormats. export const APP_DATE_FORMATS: MatDateFormats = { parse: { dat ...

Is it possible to create a progress bar in AngularJS that features several different

Seeking recommendations: I am in need of displaying a bar with three statuses using different colors all within the same bar. Any ideas? ...