How can I wait for variable to be set in a service-worker for Chrome Extension

I am building a Chrome Extension that does Speach-to-Text to a Google Document. In my service-worker I am receiving the processed text (via port messaging, so is periodic), so it can be sent to be written but I can also receive commands if the user wants to insert a new paragraph, create a bullet list, etc. When I recieve a command I have a function that manages it checkCommand(currCommand); that looks like this:

const checkCommand = (cmd) => {
const commands = {
    'foo command': () => {
        console.log('This command should create a bullet list');
        if(currListType !== null){
        callGoogleAPIScript(myToken, 'createBulletList',currListType);
        formatingMode = false;
        }
    },
    'bar command': () => {
        console.log('This command should create a new paragraph');
        callGoogleAPIScript(myToken, 'newParagraph');
        formatingMode = false;
    },
    
};
if (cmd && commands.hasOwnProperty(cmd)) {
    commands[cmd](); // needed [cmd] because split words
} else {
    console.log('Command dosen't exist');
    formatingMode = false;
}};

Note: formatingMode is used for the service-worker to know that the command has been executed and can continue dictation.
While formatingMode !== false, I am still receiving text, but now I want to set specific characteristics for my commands, for example, currListType that tells which bullet list the user chose (circle, number, etc.). How can I wait for this variable to be set in the program and then run callGoogleAPIScript(myToken, ‘createBulletList’,currListType);?
I’ve tried using a promise right before calling callGoogleAPIScript , something like this:

function waitUntilListTypeSet() {
  return new Promise((resolve, reject) => {
    const checkListType = () => {
      if (currListType !== null) {
        resolve();
      } else {
        setTimeout(checkListType, 100);
      }
    };
    try {
      checkListType();
    } catch (error) {
      reject(error);
    }
  });
}

But from what I’ve read setTimeout is unreliable in service-worker + it doesn’t work for some reason ( my currListType is set correctly globally, but promise blocks)

Why this setInterval() does not work to move the snake variable to right direction in this if statement?

I want to move snake left and right, it moves to the right direction well but when i click left it just stops and does not move left, i know that setInterval returns id but why does not it moves right ?

const snake = document.querySelector(".box");
const btns = document.querySelectorAll(".btns > button");
var X = 0;
var intervalrightId;
var intervallefttId;

btns.forEach((btn)=>{

    btn.addEventListener("click", function(e){

          if(e.target.textContent == "right"){

               if(intervallefttId){

                  clearInterval(intervallefttId)
               }


             intervalrightId = setInterval(()=>{
                  
                X += 100;
                snake.style.left = X;
            
            },500)
            
          }

          if(e.target.textContent == "left"){

                if(intervalrightId){

                    clearInterval(intervalrightId)
                }

                intervallefttId = setInterval(()=>{

                     
                    X -= 100;

                    snake.style.right = X;
                    
                },500)

          }


    })
})

React-Native-WebView is not showing any website

I just installed react-native-webview in react native . After that I trying to display the website , but its loading .

Here is my code

    import React from "react";
    import { View ,Text} from 'react-native';
    import {WebView} from 'react-native-webview';
    const WebViewComponent = () =>{
    return <WebView source={{ uri: 'https://reactnative.dev/' }} style={{ flex: 1 }} />;
    }
    export default WebViewComponent;

I just tried to display the website but its not displaying . Is there any extra dependency required to display the WebView or I just screwed up my code.

navigator.mediaDevices.getDisplayMedia does not show the current tab

My JS has the following:

   var displayMediaOptions = {
      video: {
         cursor: "always",
         height: 300,
         width: 300
      },
      audio: false
   }

   var configuration = { 
         "iceServers": [{ "url": "stun:stun2.1.google.com:19302" }]
   };

   theConn = new RTCPeerConnection(configuration); 

   const theVideo = document.getElementById('theVideo');

   theStream = await navigator.mediaDevices.getDisplayMedia(
         displayMediaOptions,
         function(stream) {
            stream.getTracks().forEach(t=>theConn.addTrack(t));
          },
          function(err) {
            alert("Not stream found");
      });

When I run this, and the Chrome pop-up with the list of selectable tabs appears, it does not show the invoking tab.

Communicate with webpage codenameone

I have an android app with a local website. I like to:
a. pass location data from java to javascript function
b. start the locationlistner from javascript.
But how is it done in codenameone? I can’t figure it out what the code is.

ad a
i like to send GPS data to the website. On the website i have the addGPS function

function getGPS(data) {
   var dat = [];
    dat = data.split(",");
    var speed = data[0];
    var heading = data[1];
    var acc = data[2];
    var lat = data[3];
    var lon = data[4];
    var myTable2 = document.getElementById("GPSdata");
    myTable2.rows[0].cells[1].innerHTML = speed;
    myTable2.rows[1].cells[1].innerHTML = heading;
    myTable2.rows[2].cells[1].innerHTML = acc;
    myTable2.rows[3].cells[1].innerHTML = lat;
    myTable2.rows[4].cells[1].innerHTML = lon;

    // add feature to map
    addGPS2(lat, lon);

}

Can i do this with a messageevent or do i have the use bc.addJSCallback method.

 String data[] = { String.valueOf( roundspd), 
 String.valueOf(Direction), String.valueOf(acc), String.valueOf(latp), 
 String.valueOf(lonp)};

 String result = "getGPS($(0))";

 bc.addJSCallback(
        result,
     Object[]{
            data.toString()
    },
    SuccesCallback.onSucces(true));

(i checked if i can use geolocation but i cant get permission for the local website (file://))

Nuxt 3 dev serve opening different project

i have issue with launch a project in nuxt 3. So i have 2 different project. when im trying to launch one project it always open the second without styles and etc. It happens in port 3000.

Even tho if i deleted the second project, it opens the 2nd one/

fetching a “href-link” from a JSON file into javascript using the XMLHttpRequest method

I’m trying to dynamically load data for my cards using javascript and JSON.
Everything works fine, loading the titles, descriptions & so on.
Now I’m having this issue where I try to dynamically add a separate link for each card
(which doesn’t seems to work as I thought it would.)

This is my html :

  <div class="navbar__container"></div>

This is the javascript I used to make it work :

let http = new XMLHttpRequest();
http.open('get', 'products.json', true);
http.send();
http.onload = function () {
    if (this.readyState == 4 && this.status == 200) {
        let products = JSON.parse(this.responseText);
        let output = "";
        for (let item of products) {
            output += `
            <div class="product">
               <img class="products__img" src="${item.image}" alt="${item.description}">
               <p class="products__title">${item.title}</p>
               <a href="${item.link}" class="products__link">Check it out!</a>
               <p class="products__usedTechnologies">USED TECHNOLOGIES</p>
               <p class="products__description">${item.description}</p>
            </div>
         `;
        }
        document.querySelector(".products").innerHTML = output;
    }
}

This is the JSON-File :

    {
    "image": "json-images/exampleImg.png",
    "title": "This is an example",
    "description": "html, css, javascript, three.js, webGL, node.js",
    "link": "href=https://bitcoin.org/nl/"
},

To make things clear, everything works except the dynamically loading of the link from the json-file, I feel the problem is based on how I call the “href” in the javascript file.

See screenshot of how it looks like:

enter image description here
The error I get when clicking the link:

enter image description here

Normally I’m quite fast on how to figure out things like this but this has been something that I can’t seem to fix, all help is appreciated

What else can eval do in js?

I want to use eval for calculation from a string, the string may contain words and letters, but I resolved that by filtering them out with regex, leaving symbols like +-/* . It worked well, but I wanted to update the program by adding more complex maths symbols like √ π % ^ °. But it throws an error. Is it that eval calculations are limited to “+-*/”? and if so, is there any alternative with respect to this question?

How to update only a field of an object format state in ReactJS?

I am using ReactJs. I am creating a form where I’m inserting the values from the user and and submitting it .

My state is of the form :

{
    firstName: "Magnus",
    lastName: "Effect",
    age: 0,
}

Right now I am using onChange function which takes the input’s name and changes the value as shown in below code.

Code

import { Row, Form, Button, Col, Nav, Navbar, Container, NavDropdown, Offcanvas } from "react-bootstrap"
import { useState, useEffect, useRef } from 'react';
import "./App.css";

export default function App() {

  const [credentials, setCredentials] = useState({
    firstName: "",
    lastName: "",
    age: 0,
  });

  const onChange = (e, key) => {
    setCredentials((prevCredentials) => ({
      ...prevCredentials,
      [key]: e.target.value + "",
    }));
    //console.log(credentials);
  };

  const handleSubmit = () => {
    console.log("FIrst Name : ", credentials.firstName);
    console.log("Last Name : ", credentials.lastName);
    console.log("Age : ", credentials.age);
  }

  const addAge = () => {
    // only want to set the age to age+3
    
    //I tried this but NOT working 
    //setCredentials(credentials.age + 3);
    
    console.log("New Age : ", credentials.age);
  }


  return <div style={{ padding: "15px" }}>


    <h1>Form</h1>

    <div className="container" >
      <div className='col-7 mx-auto border border-1 rounded-5 bg-light border-dark p-5 mb-4'>

        <Form className="fs-4">


          <Form.Group
            as={Row}
            className="mb-3"
            controlId="formBasicText"
          >
            <Form.Label column sm="4">
              First Name
            </Form.Label>
            <Col>:</Col>
            <Col sm="7">
              <Form.Control
                type="text"
                value={credentials.firstName}
                onChange={(e) => onChange(e, "firstName")}
                placeholder="Enter Name here..."
              />
            </Col>
          </Form.Group>

          <Form.Group
            as={Row}
            className="mb-3"
            controlId="formBasicText"
          >
            <Form.Label column sm="4">
              Last Name
            </Form.Label>
            <Col>:</Col>
            <Col sm="7">
              <Form.Control
                type="text"
                value={credentials.lastName}
                onChange={(e) => onChange(e, "lastName")}
                placeholder="Enter Last Name here..."
              />
            </Col>
          </Form.Group>

          <Form.Group
            as={Row}
            className="mb-3"
            controlId="formBasicText"
          >
            <Form.Label column sm="4">
              Age
            </Form.Label>
            <Col>:</Col>
            <Col sm="7">
              <Form.Control
                type="number"
                value={credentials.age}
                onChange={(e) => onChange(e, "age")}
                placeholder="Enter Age here..."
              />
            </Col>
          </Form.Group>





          <Row sm={6} className="justify-content-md-center my-3">
            <Col>
              <Button
                variant="primary"
                type="submit"

                onClick={handleSubmit}
                size="lg"
              >
                Submit
              </Button>
            </Col>

            <Col sm={8}>
              <Button
                variant="primary"
                type="submit"

                onClick={() => addAge()}
                size="lg"
              >
                Add 3 years to age.
              </Button>
            </Col>

          </Row>
        </Form>

      </div>
    </div>


  </div>
}

I want that after pressing the Add 3 yrs age should update the credentials.age state only . How can I do so?

I had tried

setCredentials(credentials.age + 3);

But it’s not working?

Find live code here

Chrome app does not affect the page of the current tab

I am creating a chrome extension app. This is how the app works:
When I click a button on the side bar, it runs a function called translator and change every text node into “test…”

When I run the function on console, it runs perfectly fine. But when I run it by clicking the button on the side bar, it runs but does not affect the appearance of the current working page.

Here are my codes:
manifest.json

{
  "manifest_version": 3,
  "name": "webpage translator",
  "version": "1.0.0",

  "permissions": [
    "contextMenus"
  ],

  "icons": {
    "16": "icons/test_icon.jpg", 
    "48": "icons/test_icon.jpg", 
    "128": "icons/test_icon.jpg"
  },

  "sidebar_action": {
    "default_page": "sidebar.html",  
    "default_icon": {         
        "16": "icons/test_icon.jpg"
    },

    "default_title": "test",     
    "use_navigation_bar": true       
  },

  "permissions": [
    "tabs",
    "activeTab",
    "scripting"
  ],
  "host_permissions": [
    "http://*/",
    "https://*/"
  ]
}

sidebar.js

import translator from "./translator.js";

const button = document.getElementById('test_button');

button.addEventListener('click', async () => {
  const [tab] = await chrome.tabs.query({
    active: true,
    currentWindow: true
  });
  console.log('current tab: ', tab);
  console.log('translator function: ', translator);
  
  await chrome.scripting.executeScript({
    target: {tabId: tab.id},
    function: translator
  });
})

console.log('starting sidebar.js...')

translator.js

async function translate(node) {
  node.textContent = 'test';
}

async function checkChildNodes(node) {
  if (node.hasChildNodes()) {
    for (let childNode of node.childNodes) {
      console.log("checking node...")
      checkChildNodes(childNode);
    }
  }
  else {
    if (node.nodeType === 3) {
      console.log('Text exists...!');
      console.log(node.textContent);
      node.textContent = 'test....!';
      translate(node);
    }
  }
}

async function translator() {
  console.log('running translator...')
  const divs = document.getElementsByTagName('div');
  for (let div of divs) {
    checkChildNodes(div);
  }
}

export default translator;

When I check the console of the current tab, I see “running translator…” message just fine. But it does not affect the text nodes of the current tab. I am quite new to chrome extension app so I must be missing something but I could not find any solution for the issue online. Any help would be greatly appreciated!

How can I create nested tree structure in table with javascript

I have a REST API and I fetch this api asynchronously and the output is a json file. I need a tabolar form table for observing this data, with the following code

let tabledata = [];
        let apidata = await load();

        for (let x=0; x<50; x++) {
            tabledata.push({
                id: x+1,
                KnowledgeArea: apidata.data[x].KnowledgeArea,
                LongName: apidata.data[x].LongName,
                Release: apidata.data[x].Release,
                colname: apidata.data[x].colname,
                tablename: apidata.data[x].tablename
            });
        }
        
        //initialize table
        var table = new Tabulator("#grid", {
            data:tabledata, //assign data to table
            autoColumns:true, //create columns from data field names
        });   

I have this table
enter image description here

I tried to have nested tree structure like this
enter image description here

then I changed the code in this way:

 for (let x=0; x<50; x++) {
                             
            tabledata.push({
                id: x+1,
                
                KnowledgeArea: apidata.data[x].KnowledgeArea,
                LongName:[{Release: apidata.data[x].Release,}],
             //   LongName: apidata.data[x].LongName,
                Release: apidata.data[x].Release,
                colname: apidata.data[x].colname,
                tablename: apidata.data[x].tablename,
              //  nested: nestedData
                
               
                
            });
        }
        
        //initialize table
        var table = new Tabulator("#grid", {
            data:tabledata, //assign data to table
            dataTree:true,
            dataTreeChildField:"childRows",
          //  autoColumns:true
        });   
    }

but I got an error for DataTree.js

DataTree.js:220 
        
       Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'getElement')
    at q.layoutRow (DataTree.js:220:13)

how can I have a nested tree table?

Nothing is getting displayed on webpage while using ember.js

I am building a simple web application using ember.js ,but in the webpage ,nothing is displayed ,in the console the following error is being displayed.I am using mirage as the back end

rsvp.js:26 Uncaught TypeError: Cannot read properties of undefined (reading 'sentence')
    at Temp.title (post.js:10:1)
    at eval (mirage-esm.js:485:24)
    at Array.forEach (<anonymous>)
    at sortAttrs (mirage-esm.js:481:22)
    at Factory.build (mirage-esm.js:388:16)
    at EmberServer.build (mirage-esm.js:7325:24)
    at EmberServer.create (mirage-esm.js:7397:30)
    at EmberServer.createList (mirage-esm.js:7466:31)
    at Object._default [as default] (default.js:9:1)
    at EmberServer.config (mirage-esm.js:7152:37

I am adding some files code here for the understanding ,
application.hbs

{{! app/templates/application.hbs }}
<div class ="jumbo">
<h2 id="title">
    My ember blog
    
</h2>
</div>

{{outlet}}

posts.js under templates

{{page-title "Posts"}}

<ul>
  {{#each @model as |post|}}
    <li>
      {{post.title}}
    </li>
  {{/each}}
</ul>
{{outlet}}

post.js under model folder in app

import Model, { attr } from '@ember-data/model';

export default class PostModel extends Model {
  @attr title;
  @attr body;
  @attr('date') publishedAt;
}

posts under routes in app folder

import Route from '@ember/routing/route';

export default class PostsRoute extends Route {
  model() {
    return this.store.findAll('post');
  }
}

posts.js under factories under mirage folder

import { Factory } from 'miragejs';

import faker from '@faker-js/faker';

export default Factory.extend({
  title() {
    return faker.lorem.sentence();
  },

  body() {
    return faker.lorem.paragraph();
  },

  publishedAt() {
    return faker.date.past();
  },
});

So these are the files that I have used in this project .and if you know the structure of emp app ,you will be able to understand these files.
My ember-cli version is 3.24.0
node: 14.21.3
os: linux x64
Please help me in resolving this ,I am beginner in ember

I don’t want to manually replace id: 1, id: 1, id: 1, into id: 1, id: 2, id: 3 in a object in vs code anymore [duplicate]

I have this code:

  {
    id: 1,
    name: 'Ken'
  },
  {
    id: 1,
    name: 'Ryu'
  },
  {
    id: 1,
    name: 'Vega'
  },

I want to make it into this:

  {
    id: 1,
    name: 'Ken'
  },
  {
    id: 2,
    name: 'Ryu'
  },
  {
    id: 3,
    name: 'Vega'
  },

I did some research on it, and turns out I can use a feature ‘find’ and ‘replace’ in vs code. You can access it from the menu bar ‘Edit’.

This is the function

In the find box, I put ‘id: d+’, and in the replace, I put ‘id: $[${++counter}]’.
However, vs code doesn’t recognize the expression. It just prints out ‘id: $[${++counter}]’, not like ‘id: 1, id: 2…’ and so on.

I don’t even know if the way I did was correct or not…

Is there anyone who knows how to do it correctly?
Thank you in advance.