How to pass variable from App Script (Javascript) into HTML?

help. I’m quite new to JS and currrently i’m still learning in passing variable between App Script to HTML and vice versa.

I have the following hello to be displayed in HTML

function test(){
  Logger.log("Test is called logger")
  console.log("Test is called console")
  return "hello" 
}

here’s how i call the html:

function doGet() {  
  var text = test()
  var htmlnya = HtmlService.createTemplateFromFile("Warna")
  htmlnya.test = text
  return htmlnya.evaluate().getContent()
}

and here’s the html page:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap demo</title>
  </head>
  <body>
    <script>
      <?= test?>
    </script>
  </body>
</html>

i’m quite confuse because some people would use google.script.run.test() and i’m trying to pass the variable using evaluate()

I would expect hello would be printed in my html page.

update:

changed the html:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap demo</title>
  </head>
  <body>
    <script>
        test
      </script>
    </script>
  </body>
</html>

and it returns

The script completed but the returned value is not a supported return type.

Why is only part of my data not showing when embed on colab from observable

This is the link to the workbook i am working on
https://observablehq.com/@kendyl-nicole-laumann-ws/working
It is trying to combine vizgen projects so that polygons and transcripts are visible on the whole model. when I embed the trancripts and polygons I want however, only the transcripts show and not the polygons.

I have tried multiple edits to make this program work. making the layers const’s, updating the deck, trying to add opacity to the polygons, changing the data. loading smaller chunks.

Why is my Ajax code not working when I included all the files needed?

Issue:
index.html works fine. I can click on button, but nothing in infodiv changes. So the Ajax code is broken!

Files location:
I run the files on my desktop visual studio code. All images are inside img folder. img folder, all the html files, ajax.js are inside Ajax folder

How I run the program:
I click index.html and choose “open in default browser” like how i run all other html files. Tried to search for if there is some commands needed in terminal to run ajax, since like no need – run regularly

index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta name="viewport" content="intial-scale=1,width=device-width">
        <script src="https://code.jquery.com/jquery-1.11.0.min.js" type="text/javascript"></script>
        <script src="ajax.js" type="text/javascript"></script>
        <title>Ajax</title>
    </head>
    <body>
        <h2>Ajax Test</h2>
        <div id="infodiv">
            Information goes here
        </div>
        <div>
            <form>
                <select name="staff" onchange="cs50Info(this.value);">
                    <option value="">Select A Dog:</option>
                    <option value="golden">Golden Retriver</option>
                    <option value="bernese">Bernese Mountain Dog</option>
                    <option value="samoyed">Samoyed</option>
                    <option value="husky">Husky</option>
                </select>
            </form>
        </div>

    </body>
</html>

ajax.js

function cs50Info(name)
{
    //deal with the situation where nothing is chosen
    if (name === "")
        return;

    // create a new AJAX object
    var ajax= new XMLHttpRequest();

    // change content inside the infodiv
    ajax.onreadystatechange = function() {
        if (ajax.readyState === 4 && ajax.status === 200) {
            $('infodiv').html(ajax.responseText);
        }
    }
    //open the requested file and going to update just the infodiv
    ajax.open('GET', name + '.html', true);
    ajax.send();
}

golden.html example: (all other ones are similar)

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta name="viewport" content="intial-scale=1,width=device-width">
        <title>Dogs</title>
    </head>
    <body>

   <p>Golden Retriver</p> 
   <img src="img/golden.jpeg">
   <p>Golden Fluffy Retriever</p>
   <p>So Adorable!</p>
</body>
</html>

plugin vscode global variables

This is a part of my code of ectension.ts in the out folder:

Object.defineProperty(exports, "__esModule", { value: true });
exports.activate = void 0;
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require("vscode");
const path = require("path");
//path for the media of the button in treeview (HOME)
const HomeItem = path.join(path.dirname(__dirname), 'media/home.png');
//generate the treeview to see different button or only one in the primary sidebar
console.log(HomeItem);

let rememberLearningPath = '';
let rememberId = '';
let rememberTypeQuiz = '';
let rememberTipologyQuiz = '';
let checkNode = false;
let descriptionRem = '';



// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
function activate(context) {
    // Use the console to output diagnostic information (console.log) and errors (console.error)
    // This line of code will only be executed once when your extension is activated
    console.log('Congratulations, your extension "helloworld-sample" is now active!');
    //register the command to show the treeview component
    vscode.window.registerTreeDataProvider('nodeDependencies', new TreeDataProvider());
    vscode.commands.registerCommand('treeExplorer.openFile', (resource) => {
        vscode.window.showTextDocument(resource);
    });
    // The command has been defined in the package.json file
    // Now provide the implementation of the command with registerCommand
    // The commandId parameter must match the command field in package.json
    const disposable = vscode.commands.registerCommand('extension.helloWorld', () => {
        // The code you place here will be executed every time your command is executed
        // Display a message box to the user
        vscode.window.showErrorMessage("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
    });
    //command to launch the extension code 
    vscode.commands.registerCommand('extension.welcome', () => {
        const panel = vscode.window.createWebviewPanel('welcome', 'welcome', vscode.ViewColumn.One, { enableScripts: true });
        panel.title = 'Polyglot';
        panel.webview.html = getWebviewContent();
        //to comunicacion between webview and the vscode ts file
        panel.webview.onDidReceiveMessage(message => {
            //console.log(message);
            //switch to understand what command was send
            switch (message.command) {
                //when the message is apriNotebook you do his actions
                case 'apriNotebook':
                    
//const htmlPath = vscode.Uri.joinPath(context.extensionUri,'notebooks', 'ciao.ipynb');
                    //vscode.commands.executeCommand('vscode.open', htmlPath);
                    
                    /*const notebookPath = vscode.Uri.joinPath(context.extensionUri, 'notebook', 'menunote.html');

                    vscode.env.openExternal(notebookPath);
                    */

                    console.log('Received apriNotebook command. elementoCliccato:', message.elementoCliccato);

                    rememberLearningPath = message.elementoCliccato;

                    console.log('Received aprNotebook command. idElementoCliccato:', message.idElementoCliccato);

                    rememberId = message.idElementoCliccato;

                    //rememberId = '3aaa2e43-3be9-4b52-87c9-c88eeafa6e60';
                    console.log(rememberId);

                    descriptionRem = message.description;
                    console.log('descnote',descriptionRem);

                    v

    })

    context.subscriptions.push(disposable);
}


exports.activate = activate;

//# sourceMappingURL=extension.js.map

i use this code to create my vsix file to upload the extension on marketplace.

the problem is that when i open my plugin i have error at line 105 because he say that my rememberLearningPath variable doesn’t exist. in fact, the code print the line first and next block everything
SOmeone can help me? there is a way to see this variable?
thank you all.

I try to change the variable in var and other

Vue.js v-html not rendering line breaks () in dynamically injected HTML content

I have a component that highlights code:

<template>
  <div class="mx-auto h-[30rem] w-[30rem] border-2 border-black">
    <code-highlight language="javascript">
      <code>
        <p v-html="html"></p>
      </code>
    </code-highlight>
  </div>
</template>

<script setup>
import CodeHighlight from 'vue-code-highlight/src/CodeHighlight.vue'
import 'vue-code-highlight/themes/duotone-sea.css'
import 'vue-code-highlight/themes/window.css'
const props = defineProps(['html'])
</script>

<style lang="scss" scoped></style>

and the use:

<code-example :html=html>
              </code-example>

html is

<p><em>[a-zA-Z]&nbsp;&nbsp;</em>any letter a-z and A-Z<br> [0-9] means any number<br>[a-z0-9] any letter a-z or number 0-8<br>[a-zA-Z0-9_] any leeter a-z and A_Z, any number 0-9 and "_"</p>

and any of the <br> tags are not executed. The tags is a one long line, the component doesnt change its size, it only has a 10% of a div. Why <br> tags or "/n" are not executed and the component doesn’t change hight?

I tried changing <p> to <div> or different structure but it didn’t work…

The MutationObserver is not triggered when innerHTML is used by the documentElement node

I’ve discovered the MutationObserver interface for intercepting and analyzing changes in the DOM.

It works very well and I’ve managed to intercept all DOM changes… with the exception of the DOM change via the innerHTML method when it’s the documentElement node that uses it.

Here is my code:

function test() {

  const config = {
    subtree: true,
    childList: true
  };

  const callback = (mutationList) => {
    for (const mutation of mutationList) {
      if (mutation.type === "childList") {

        for (const node of mutation.addedNodes) {
          if (node.tagName && node.tagName.toLowerCase() === "div") {
            console.log(node);
          }
        }
      }
    }
  };
  const observer = new MutationObserver(callback);
  observer.observe(document.documentElement, config);
};

test();

document.documentElement.innerHTML += '<div>TEST</div>';
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>MutationObserver Example</title>
</head>

<body>
</body>

</html>

The following JavaScript code:

document.documentElement.innerHTML += '<div>TEST</div>';

appears to completely rewrite the HEAD and BODY nodes.
This explains why the MutationObserver interface fails to intercept the addition of a <div> tag.

I’d like to know how to intercept in this case, the addition of a <div> tag to the DOM.

Photoshop Script rename and export Artboard to PNG

I try to create a Photoshop Script to rename and export all Artboards to png.
the Rename Function works well and the export too except the size of each Artboards…
thanks a lot for your support

`// CREATE USER INTERFACE
(function () {
var title = “Script”;

// Reusable UI variables.
var g; // group
var p; // panel
var w; // window

// Permanent UI variables.
var btnCancel;
var btnOk;
var inpTitle;
var inpSeason;
var inpLanguage;

// CREATE USER INTERFACE
w = new Window("dialog", title);
w.alignChildren = "fill";
p = w.add("panel");
g = p.add("group");
g.add("statictext", undefined, "Title :");
inpTitle = g.add("edittext");
inpTitle.characters = 15;
g = p.add("group");
g.add("statictext", undefined, "Season :");
inpSeason = g.add("edittext");
inpSeason.characters = 15;
g = p.add("group");
g.add("statictext", undefined, "Language :");
inpLanguage = g.add("edittext");
inpLanguage.characters = 15;
g = w.add("group");
g.alignment = "center";
btnOk = g.add("button", undefined, "Ok");
btnCancel = g.add("button", undefined, "Cancel");

// UI EVENT HANDLERS
btnOk.onClick = function () {
    w.close(1);
};
btnCancel.onClick = function () {
    w.close(0);
};

// Show THE WINDOW
if (w.show() == 1) {
    process();
}

function process() {
    var doc = app.activeDocument;
    var layers = doc.layers;

    // Calculate the total number of artboards
    var totalArtboards = 0;
    for (var i = 0, l = layers.length; i < l; i++) {
        doc.activeLayer = layers[i];
        if (isArtBoard(doc.activeLayer)) {
            totalArtboards++;
        }
    }

    // Process artboards with a progress bar
    var progressBar = new ProgressBar("Processing...", totalArtboards);
    try {
        for (var i = 0, l = layers.length; i < l; i++) {
            doc.activeLayer = layers[i];
            if (isArtBoard(doc.activeLayer)) {
                // Update progress bar
                progressBar.update(i - 1);

                // Change the artboard name
                doc.activeLayer.name = inpTitle.text + "_" + inpSeason.text + "_Main_" + doc.activeLayer.name;

                // Export the artboard as PNG
                exportArtboardToPNG(doc, doc.activeLayer, inpTitle.text + "_" + inpSeason.text + "_Main_" + doc.activeLayer.name + "_" + inpLanguage.text);
            }
        }
    } finally {
        // Close progress bar
        progressBar.close();
    }
}

function exportArtboardToPNG(doc, layer, filename) {
    var exportOptions = new ExportOptionsSaveForWeb();
    exportOptions.format = SaveDocumentType.PNG;
    exportOptions.PNG8 = false;
    exportOptions.transparency = true;
    exportOptions.interlaced = false;
    exportOptions.quality = 100;

    // Save current ruler unit
    var originalRulerUnits = app.preferences.rulerUnits;
    app.preferences.rulerUnits = Units.PIXELS;

    // Check if the layer is an artboard
    if (isArtBoard(layer)) {
        // Set canvas size to match layer dimensions
        var bounds = layer.bounds;
        var width = bounds[2] - bounds[0];
        var height = bounds[1] - bounds[3];
        doc.resizeCanvas(width, height, AnchorPosition.TOPLEFT);

        // Export the layer as PNG
        var exportFile = new File(doc.path + "/" + filename + ".png");
        doc.exportDocument(exportFile, ExportType.SAVEFORWEB, exportOptions);

        // Restore original ruler unit
        app.preferences.rulerUnits = originalRulerUnits;

        // Undo the resizeCanvas to keep the original document intact
        doc.activeHistoryState = doc.historyStates[doc.historyStates.length - 2];
    } else {
        alert("Unable to export layer. Make sure the layer is an artboard or text layer.");
    }
}

function isArtBoard(layer) {
    // Check if the layer is an artboard
    try {
        return layer.isBackgroundLayer || layer.grouped || layer.layers.length > 0;
    } catch (e) {
        return false;
    }
}

function ProgressBar(title, maxSteps) {
    this.window = new Window("palette", title);
    this.progress = this.window.add("progressbar", undefined, 0, maxSteps);
    this.progress.maximumSize.width = 300;
    this.window.show();

    this.update = function (step) {
        this.progress.value = step;
        this.window.update();
    };

    this.close = function () {
        this.window.close();
    };
}

})();`

I’m not a developer X_x hope someone could help thanks a lot

Access Object value in a string and compare

var siteList = {};
var siteInfo = [];
var part_str = '[{"part":"00000PD","partSupplier":"DELL"}]';
var part = part_str.substring(1, part_str.length - 1);

eval('var partobj=' + part);
console.log(partobj.part);
console.log(partobj.partSupplier);

This works fine.
But I have to find if the part number matches from the following part, the partSupplier will be added to the following json else not.

if (partobj.partnumber.includes("00000PD")) {
    var partSupp = partobj.partSupplier;
} else {
    partSupp = "HP";
}

siteInfo = {
    "Parts_Num": part,
    "partSupplier": partSupp
}
siteList.siteInfo.push(siteInfo);

I tried the following but partSupplier value is empty:

if (partobj.partSupplier.includes("00000PD")) {
    var partSupp = [partobj.partSupplier];
    console.log('partSupp' || partSupp);
    else
        partSupp = "HP";
}

The result from console is:
partSupp
It does not return any value.

Iterating array of objects and joining the key values with commas

I have an array of objects containing addresses like this:

let addressArray = [
  {
    street: '123 Charm St',
    city: 'Tuscaloosa',
    state: 'AL'
  },
  {
    street: '456 Hampton Ave',
    city: 'Tuscaloosa',
    state: 'AL'
  },
  {
    street: '789 Greenview Dr',
    city: 'Austin',
    state: 'TX'
  }
]

I want to join each the key values into a single string with comma delimeters like this:

streets = '123 Charm St,456 Hampton Ave,789 Greenview Dr'
cities = 'Tuscaloosa,Tuscaloosa,Austin'
states = 'AL,AL,TX'

Currently I map three times (once for each key) and join each value by comma like this:

const streets = addressArray.map((elem) => elem.street).join(",");
const cities = addressArray.map((elem) => elem.city).join(",");
const states = addressArray.map((elem) => elem.state).join(",");

Is there a more concise way of doing this? So I don’t have 3 repetitive map calls?

Note: If there are empty values, it should still separate the empty value with comma, for example:

let addressArray = [
  {
    street: '',
    city: 'Tuscaloosa',
    state: 'AL'
  },
  {
    street: '456 Hampton Ave',
    city: 'Tuscaloosa',
    state: 'AL'
  },
  {
    street: '789 Greenview Dr',
    city: 'Austin',
    state: 'TX'
  }
]

The streets string for the above array should be ,456 Hampton Ave,789 Greenview Dr

Merging an external .pdf file in my generated pdf (react-pdf)?

So I successfully generated my PDF file using react-pdf library. I built it using , , and other components from react-pdf .

The thing is, there are some external .pdf files that i have to “append” at the end of my generated file. I didn’t find an exact solution online. There is one stipulation and that is that this .pdf shouldn’t be converted to an image, it should be selectable just like the generated pdf already is.

Is this achievable using just react-pdf or is there a workaround?

How to make a video overlay, preserving the overlay sound?

I’m using fluent-ffmpeg library for NodeJS, trying to overlay the video, but also need to set the audio from the overlay to the main video

ffmpeg()
.input(mainVideo)
.input(pipVideo)
.complexFilter([
 {
  'filter': 'overlay', 
  'options': {'x':0, 'y':0, 'eof_action': 'pass'},
  'inputs':['0:v', '1:v'],
  'outputs': 'output'
 }
], 'output')
.saveToFile(outputFile) //output filepath
.on('end', function (err, stdout, stderr) { //on the end of video generation
  console.log('done')
})
.on('error', function(err) {
  throw new Error(err.message)
})

Need Javascript Code to Close One Toggle When Another is Opened [closed]

I have a bunch of toggles on a page. I am building with the Divi builder if that helps at all.

Right now, when one toggle is opened and you go to open another, the previous one stays open unless you manually close it.

I’d like some javascript code which would make the already opened toggle automatically close when the new one is opened.

Thanks in advance!

I’ve tried some various javascript codes that I found here, but none of them seemed to work. (I might just not know how to customize them for my needs)

how to export an array from nodejs (server.js) to regular javascript(myscript.js)

I’m reading a line on NodeJS and insert it into an array however i need to export it to JavaScript file in order to use it there. however I’m having difficulty since the array arrives but outside the function it’s empty. so I’m wondering if anyone is able to fix this issue or help another way to send this array from NodeJS to JavaScript.

const test = [];
export function message(n){
      
      for (var i = 0; i< n.length; i++){
            test[i] = n[0];
      }   
      //works
      console.log(test[0]);
      
}
//outside of function 
//doesn't work
console.log(test[0]);

I was hoping to access the array outside the function and be able to utilized all it’s features.