async/await consecutive fetch calls: how to?

As an example, suppose that i want to build a dynamic HTML pages showing the properties of all the planets and moons of the solar system, loading the data from an observatiry server API.

I do a GET request to get a json containing all the planets of the solar system.
I then need to loop each planet to write the HTML page, but i need to do a GET request to get another json object containing all the moons of a given planet.

So, my code looks like this:

    async function GetPlanets(Star) {
        const response = await fetch('https://observatory.app/api/planets?name=${Star}');
        var data = await response.json();
        showPlanets(data);  // This function writes the innerhtml of a table, 
    }
         
    async function GetMoons(Planet) {
        const response = await fetch('https://observatory.app/api/moons?name=${Planet}');
        var data = await response.json();
        return showMoons(data);  // This function writes the innerhtml of a table
    }
         
    function showPlanets(data) {
        let tab =
          `<thead><tr>
           <th>name     </th>
           <th>mass     </th>
           <th>gravity  </th>
           <th>moons    </th>
           </tr></thead>
          `;
        // Loop to access all the planets
        tab += `<tbody>`;
        for (let r of data.all_planets) {
            tab += `<tr>
            <td rowspan=2> ${r.name         }</td>
            <td> ${r.mass                   }</td>
            <td> ${(r.gravity).toFixed(2)   }</td>
            </tr>`;
            
            // Now add the moons
            tab += `<tr><td id="moons" colspan=3>`
            tab += GetMoons(r.name); // GET the moons of this planet
            tab += `</td></tr>`;
        }
        tab += `</tbody>`;
        // Setting innerHTML as tab variable
        document.getElementById("systemPlanets").innerHTML = tab;
    }
         
    function showMoons(data) {
        let tab =
          `<table><thead><tr>
           <th>name     </th>
           <th>mass     </th>
           <th>gravity  </th>
           </tr></thead>
          `;
        // Loop to access all the moons
        tab += `<tbody>`;
        for (let r of data.all_moons) {
            tab += `<tr>
            <td> ${r.name                   }</td>
            <td> ${r.mass                   }</td>
            <td> ${(r.gravity).toFixed(2)   }</td>
            </tr>`;
        }
        tab += `</tbody></table>`;
        return tab;
    }

At the end of the <body> section there’s the call to getPLanets(Sol); and the page should then show the data.

Now, i see that all the request receives an answer, but my page did not get built. I see the planet table for a brief moment and then it just show “undefined”.

Searching for a solution I learned that async function cannot return a value, and also I think I’ve understood that the async functions should not be called in the way I do, but really i know nothing about promises and async/await so I’m struggling to get what should I do.
For what i’m understanding, I don’t want to have all the request in parallel, instead i just want to process each planet/moon one at time…

How can i do all the GET requests after the first one and write the data in the page?

remove and add html element in java script [closed]

Intenté proporcionar un ejemplo claro de cómo agregar y eliminar clases de un elemento HTML utilizando JavaScript. Esperaba que al seguir los pasos proporcionados, los usuarios pudieran comprender cómo usar la propiedad classList para lograr este objetivo. Lo que realmente resultó fue una explicación detallada de cómo agregar y eliminar clases, sin embargo, omití describir explícitamente el proceso de agregar clases en el contexto de un escenario específico de desarrollo web.—————————————————————————————————————————————————————————————————————————————————————————————————————————————————

Add ID to parent Iframe youtube

I need to add a class.

Like this :

<iframe width="480" height="270" src="https://www.youtube.com/">
</iframe>

To

<div class="video-class">
<iframe width="480" height="270" src="https://www.youtube.com/">
</iframe>
</div>

Thanks for help

why is my function returning HTML file instead of error/json?

When my login function encounters an error, such as when the email or password is missing, or when the student does not exist or their email is not verified, the response from the server is in HTML format instead of JSON. This HTML response includes an error message along with a stack trace, which is not suitable for consumption by frontend applications expecting JSON responses.

const asyncHandler = (requestHandler) => {
    return (req,res,next) => {
        Promise.resolve(requestHandler(req,res,next)). 
        catch((err)=>next(err))
    }
}

export {asyncHandler}

the ApiError class to throw custom error messages

class ApiError extends Error{
    constructor(
        statusCode,
        message = "Something went wrong",
        errors = [],
        stack = ""
    ){
        super(message)
        this.statusCode = statusCode
        this.data = null,
        this.message = message 
        this.success = false
        this.errors = errors

        if(stack){
            this.stack = stack
        }
        else{
            Error.captureStackTrace(this,this.constructor)
        }

    }
}

export {ApiError}

login function, it works fine but not when in error handling

const login = asyncHandler(async(req,res) => {

    const {Email, Password} = req.body;

    /*if(!Email){
        throw new ApiError(400,"E-mail is required")
    }
    if(!Password){
        throw new ApiError(400,"Password is required")
    }*/

    const result = await authSchema.validateAsync(req.body)

    const StdLogin = await student.findOne({
        Email
    })

    if(!StdLogin){
        throw new ApiError(400, "Student does not exist")
    }

    if(!StdLogin.Isverified){
        throw new ApiError(401, "Email is not verified");
    }

    const StdPassCheck = await StdLogin.isPasswordCorrect(Password)

    if(!StdPassCheck){
        return res.status(400).json({ error: "Password is incorrect" });
    }

    const tempStd = StdLogin._id

    
    const {Accesstoken, Refreshtoken} =  await generateAccessAndRefreshTokens(tempStd)

    const loggedInStd = await student.findById(tempStd).select(-Password -Refreshtoken)

    const options = {
        httpOnly:true,
        secure:true,
    }

    return res
    .status(200)
    .cookie("Accesstoken", Accesstoken, options)
    .cookie("Refreshtoken", Refreshtoken, options)
    .json(
        new ApiResponse(
            200,{
            user:loggedInStd
            }, "logged in"
            )
    )

})

RESPONSE I AM GETTING INCASE OF ERROR:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Error</title>
</head>

<body>
    <pre>Error: Student does not exist<br> &nbsp; &nbsp;at file:///C:/parag/CollegeProject/e-Learning-Platform/backend/src/controllers/student.controller.js:133:15<br> &nbsp; &nbsp;at process.processTicksAndRejections (node:internal/process/task_queues:95:5)</pre>
</body>

</html>

I want the function to return error or json data incase of error

Unable to insert data in array field in snowflake table using javascript

let gpt3Embedding= async (content) => {
    try {
        const response =  openai.embeddings.create({
            model: "text-embedding-ada-002",
            input: content,
            encoding_format: 'float',
        });
        const vector = response.data[0]['embedding']; 
        return vector;
    } catch (error) {
        console.error('Error:', error);
        throw error;
    }
}



router.post('/saveChat', async (req, res) => {
    try {
        if (req.session.isAuthenticated) {
            let sql_text = "";
            const chats = req.body;
            var result = null;
            let empty_arr=[];
            console.log(chats)
            let create_by = req.session.account.localAccountId
            if (Object.keys(chats.session).length > 0) {
                // check if Session exists if not create a new one

                const conn = await mainConnection();
                result = await conn.execute(`select count(session_id) as cnt from CHAT_SESSION_PWT where session_id='${chats.session.session_id}' and created_by='${create_by}'`);

                console.log(result)
                console.log(`select count(session_id) from CHAT_SESSION_PWT where session_id='${chats.session.session_id}' and created_by='${create_by}'`);

                if (result[0].CNT == 0) {
                    sql_text = `insert into CHAT_SESSION_PWT (session_id,session_name,create_on,created_by)
                    VALUES ('${chats.session.session_id}','${chats.session.session_name}',CURRENT_TIMESTAMP ,'${create_by}')`
                    result = await conn.execute(sql_text);
                }
                
                if (chats.chat.length > 0) {                    
                    sql_text = `INSERT INTO user_chat_pwt (
                        chat_id,
                        chat_question_id,
                        session_id,
                        chat_role,
                        content,
                        content_raw,
                        documents,
                        query_embedding,                        
                        chat_like,
                        dislike,
                        pin,
                        response_table,
                        insights,
                        graph,                      
                        steps,
                        knowledge_base,
                        usage,
                        sequence_no,
                        query_category,
                        question,
                        resTime
                    ) VALUES `;

                    for (let i in chats.chat) {
                         let vec = [];
                        await gpt3Embedding(chats.chat[i].content).then(vector => vec=vector);
                        sql_text += `(
                        '${chats.chat[i].chat_id}',
                        '${chats.chat[i].chat_question_id}',
                        '${chats.session.session_id}',
                        '${chats.chat[i].chat_role}',
                        '${chats.chat[i].content}',
                        '${JSON.stringify(chats.chat[i].content_raw).replace(/'/g, """)}',
                        '${JSON.stringify(chats.chat[i].documents).replace(/'/g, """)}',
                        '${JSON.stringify([vec])}',
                        ${chats.chat[i].chat_like},
                        ${chats.chat[i].dislike},
                        ${chats.chat[i].pin},
                        '${JSON.stringify(chats.chat[i].response_table).replace(/'/g, """)}',
                        '${chats.chat[i].insights}',
                        '${JSON.stringify(chats.chat[i].graph).replace(/'/g, """)}',                      
                        '${(chats.chat[i].steps).replace(/'/g, """)}',
                        '${(chats.chat[i].knowledge_base).replace(/'/g, """)}',
                        '${JSON.stringify(chats.chat[i].usage).replace(/'/g, """)}',
                        ${chats.chat[i].sequence_no},
                        '${chats.chat[i].query_category}',
                        '${chats.chat[i].question}',
                        ${chats.chat[i].resTime}
                        ),`
                    }

                    sql_text = sql_text.substring(0, sql_text.length - 1)
                    console.log("x1b[31m", sql_text);
                    result = await conn.execute(sql_text);
                }


                closeConnection(conn);

                return res.status(200).json({
                    status: true,
                    data: result,
                });

            }
            else {
                return res.status(500).json({
                    status: false,
                    error: "No chats availabe to save",
                });
            }
        } else {
            return res.status(500).json({
                status: false,
                error: 'unauthorised',
            });
        }

    } catch (err) {
        return res.status(500).json({
            status: false,
            error: err,
        });
    }

});


I have been trying to insert an array in vector column (Array type ) in snowflake database.
The array has been generated using await gpt3Embedding(chats.chat[i].content).then(vector => vec=vector);
The insert is at ‘${JSON.stringify(vec)}’,

The save is failing with 500 error.

The error details at console is
{status: false, error: {}}
error : {}
status : false

The only successful way of adding data was using the hardcoding –
‘${JSON.stringify([0.013054623,0.020803465,-0.01879506,-0.02726333,-0.0029545266,0.021477928,0.006006476,-0.012222785,-0.013736581])}’,

Expecting the data to be inserted in the snowflake table .

Can I set onclick handler to the entire Notify Quasar element instead of triggering an API button

I have a Notify element inside the page, clicking on the entire Notify div I need to run a function (from a Pinia store). So now the click is set to the label (button) element, but I need to place the click handler on the entire Notify element. And I’d also like to understand how to add a css hover effect on the entire Notify element, as the “.q-notify:hover { cursor: pointer !important;} ” – doesn’t work

const showNotify = {
  info(index: any) {
    Notify.create({
      type: 'info',
      icon: '',
      message: title,
      caption: getCaption(data),
      timeout: 3000,
      actions: [
        {
          noDismiss: true,
          label: 'Open Sidebar', // don't need this label instead
          handler: () => {
            notificationsStore.openSidebarNotifications()
          },
        },
      ],
    })
    setTimeout(() => {
      showNotify.info(index + 1)
    }, 1000)
  },
}

How to fetch specific header tag data from a server by a given url?

Given any blog post, e.g. this example. I’m currently fetching the document by url and parsing the string with a DOM parser to ‘text/html’.

For the given example page I want to fetch the image, I retrieve the image url like so

const image = doc.querySelector('meta[property="og:image"]');
const imageUrl = image.getAttribute("content");

I also want to search for a JSON schema following the schema.org specification. For the given example page I want to fetch a recipe schema

const schema = doc.querySelector('script[type="application/ld+json"]');
const parsedSchema = JSON.parse(schema?.textContent ?? "");
const recipe = parsedSchema["@graph"]?.find((item: any) => item["@type"] === "Recipe");

I want to retrieve data from different blog pages so I would have to maintain multiple implementations.

Unfortunately I wasn’t able to find a network request ( Chrome network tab ) that fetches this information. But is there a way to ask for that data directly so I don’t have to search the HTML DOM?

Clarification about main uses of service workers

recently I’ve taken a look at service workers and am thinking about leveraging them, in particular being able to proxy the network requests. If the response returns specific meta-data then service worker would broadcast a message to a browser tab and perform an action on the user’s screen. This must happen always. However doing some research it looks to not be the right approach as service workers should not be used for critical features (which in this case here it is). They’re more of a complement which explains why they’re commonly used as caching to improve offline experience.

I’m looking for answers on why service workers can’t be depended on for critical features. Is it browser support? Or do users just commonly disable service workers?

How to Change Page Source View?

I am coding a site with Nuxt3 and I have a question about the source section.

enter image description here

When I inspect the item, it appears like this, but when I look at other pages, it usually shows 1 page. How do they do this?

I researched code obfuscation but could not get the result I wanted.

Angular Drag and Drop: Arrays Not Updating Dynamically in Template despite Length Changing Correctly

I have implemented Angular Drag and Drop feature following Angular docs https://material.angular.io/cdk/drag-drop/overview#cdk-drag-drop-connected-sorting-group.

html looks like:

 <div
    class="example-container flex flex-col text-center h-fit min-h-[10rem] w-[15%] border-2 border-gray-100 rounded-md shadow-md"
  >
    <h2
      class="text-xl font-semibold mx-auto py-4 bg-green-100 w-full drop-shadow-md"
    >
      Monday
    </h2>
    <div
      cdkDropList
      [cdkDropListData]="Monday"
      class="example-list bg-red-100 min-h-[5rem]"
      (cdkDropListDropped)="drop($event)"
    >
      @for (item of Monday; track item) {

      <app-drag-drop-item [title]="item" cdkDrag></app-drag-drop-item>
      }
    </div>
  </div>

and second container:

<div
    class="example-container flex flex-col text-center h-fit min-h-[10rem] w-[15%] border-2 border-gray-100 rounded-md shadow-md"
  >
    <h2
      class="text-xl font-semibold mx-auto py-4 bg-blue-100 w-full drop-shadow-md"
    >
      Tuesday
    </h2>
    <div
      cdkDropList
      [cdkDropListData]="Tuesday"
      class="example-list bg-red-100 min-h-[5rem]"
      (cdkDropListDropped)="drop($event)"
    >
      @for (item of Tuesday; track item) {

      <app-drag-drop-item [title]="item" cdkDrag></app-drag-drop-item>
      }
    </div>
  </div>

I have two days and taks for each day, that are stored in an array:

  Monday = ['Refractoring'];
  Tuesday = ['Gym'];

the component.ts file

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import {
  CdkDragDrop,
  CdkDrag,
  CdkDropList,
  CdkDropListGroup,
  moveItemInArray,
  transferArrayItem,
} from '@angular/cdk/drag-drop';
import { DragDropItemComponent } from '../drag-drop-item/drag-drop-item.component';
import { MatIconModule } from '@angular/material/icon';
import { FormsModule } from '@angular/forms';
import { AddTaskFormComponent } from '../add-task-form/add-task-form.component';
import { TaskService } from '../../../../shared/services/task.service';

@Component({
  selector: 'app-dashboard-space',
  standalone: true,
  imports: [
    CdkDropListGroup,
    CdkDropList,
    CdkDrag,
    DragDropItemComponent,
    DragDropItemComponent,
    MatIconModule,
    FormsModule,
    AddTaskFormComponent,
    CommonModule,
  ],
  templateUrl: './dashboard-space.component.html',
  styleUrl: './dashboard-space.component.css',
})
export class DashboardSpaceComponent {
  constructor(private e: TaskService) {
    this.tasks = this.e.getTasks();
  }

  tasks: any[];

  todo = ['Get to work', 'Pick up groceries', 'Go home', 'Fall asleep'];

  Monday = ['Refractoring'];
  Tuesday = ['Gym'];
  Wednesday = ['Interview'];
  Thursday = ['TV'];
  Friday = ['Sport'];

  done = ['Get up', 'Brush teeth', 'Take a shower', 'Check e-mail', 'Walk dog'];

  newTask: string = '';

  addNewTask() {
    this.todo.push(this.newTask);
  }

  handleFormSubmission(formData: any) {
    this.todo.push(formData);
  }

  drop(event: CdkDragDrop<string[]>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(
        event.container.data,
        event.previousIndex,
        event.currentIndex,
      );
    } else {
      transferArrayItem(
        event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex,
      );
    }
  }
}

I follow arrays with:

  <h1>{{ Monday }}</h1>
  <h1>{{ Tuesday }}</h1>

but i see no changes. So moving an item from one array to another doesnt actuall change the array.
But if I do <h1>{{ Monday.length }}</h1> or <h1>{{ Tuesday.length }}</h1> and i move one item for one array to another the length changes properly.
So now i have the question, why Angular properly follow and update the length of an array, but doesnt follow, update and then show to actuall value of the arrays.

TypeError: Cannot read properties of undefined (reading ‘length’) in packet protocol

I’m getting the error TypeError: Cannot read properties of undefined (reading ‘length’) on line 25 but that same function works fine on line 15.

var zeroBuffer = Buffer.from('00', 'hex')

module.exports = packet = {

    //params is an array of objects to be turned in to packets/buffers/whatever
    build: function(params){
        var packetParts = []
        var packetSize = 0

        params.forEach(function(param){
            var buffer;

            if(typeof param === 'string'){
                buffer = Buffer.alloc(param.length, param, 'utf8')
                buffer = Buffer.concat([buffer, zeroBuffer], buffer.length + 1)
            }
            else if (typeof param === 'number'){
                buffer = Buffer.alloc(2)
                buffer.writeUInt16LE(param, 0)
            }
            else {
                console.log('Warning: Unknown data type in packet builder')
            }

            packetSize += buffer.length;
            packetParts.push(buffer);
        })

        var dataBuffer = Buffer.concat(packetParts, packetSize)

        var size = Buffer.alloc(1)
        size.writeUint8(dataBuffer.length + 1, 0)

        var finalPacket = Buffer.concat([size, dataBuffer], size.length + dataBuffer.length)

        return finalPacket;
    }
}

This is the packet protocol of a larger project I’ve been working on from a tutorial series. It is out of date but I’ve yet to have issues bringing it up to date until now. I’ve watched the tutorial about 3 times over just trying to catch what I did wrong but I can’t figure it out for the life of me.

Tutorial playlist is https://www.youtube.com/watch?v=EyNVeTzhC1w&list=PLLUWsMtogf9jQGzn3nAjAw2_aq3PM08pC&index=2
The piece with the error pops up in part 5 around 13:00

Pressing Escape manually dismisses a prompt outside the DOM but if done through Puppeteer it has no effect. Why & how to allow it to have an effect?

When I manually sign into Slack through the browser I’m able to hit the escape key to make the Chrome prompt which is outside the DOM go away. But when using Puppeteer programmatically hitting the escape key via page.keyboard.press('Escape') has zero effect. I’m wondering if I’m not thinking of something else that needs to happen in order for the press to register.

Going through SO I do see others with similar issues. And since these prompts are outside the DOM the consensus is that there’s really nothing Puppeteer can do. But seeing how I’m able to hit the escape key to make the prompt go away I’m wondering if there is something there.

enter image description here

How to generate excel file using exceljs and node js

I want to create excel file like this,
enter image description here

Below is how my data looks,

{
  "property_id": 2,
  "venue": "CGAP",
  "deposits": [
    {
      "bc_customer_id": "TR-P0002",
      "ae_customer_id": 1177,
      "customer_name": "PETRONAS DAGANGAN BERHAD",
      "subscription_id": 5508,
      "agreement_no": "AP600176",
      "start_date": "2021-09-01T00:00:00.000Z",
      "end_date": "2023-08-31T23:59:59.000Z",
      "subs_month_prices": [
        {
          "subscription_id": 5508,
          "price": 44653.84,
          "product": "DEPOSIT - SECURITY DEPOSIT",
          "charge_code": "CG051",
          "status": 0
        },
        {
          "subscription_id": 5508,
          "price": 1796,
          "product": "DEPOSIT - SECURITY DEPOSIT",
          "charge_code": "CG051",
          "status": 0
        }
      ]
    },
    {
      "bc_customer_id": "TR-A0016",
      "ae_customer_id": 1445,
      "customer_name": "AKMAL AZMI",
      "subscription_id": 6351,
      "agreement_no": "AP600196",
      "start_date": "2022-03-01T00:00:00.000Z",
      "end_date": "2023-02-28T23:59:59.000Z",
      "subs_month_prices": [
        {
          "subscription_id": 6351,
          "price": 50,
          "product": "DEPOSIT - ACCESS CARD",
          "charge_code": "CG001",
          "status": 0
        },
        {
          "subscription_id": 6351,
          "price": 2000,
          "product": "DEPOSIT - SECURITY DEPOSIT",
          "charge_code": "CG051",
          "status": 0
        }
      ]
    }
  ]
}

This is my code,

async function generateSpreadsheet(params, ctx, opts) {
  const { data } = params

  const workbook = new Exceljs.Workbook()
  data.forEach(d => {
    const { venue, deposits } = d
    const worksheet = workbook.addWorksheet(venue)

    const columns = [
      { name: 'Customer' },
      { name: 'Customer ID' },
      { name: 'BC Customer ID' },
      { name: 'Subscription ID' },
      { name: 'Agreement No.' },
      { name: 'Deposit' },
      { name: 'Item Code' },
      { name: 'Amount' },
      { name: 'Status' },
    ]

    const rows = deposits.map(d => {
      const {
        customer_name,
        ae_customer_id,
        bc_customer_id,
        subscription_id,
        agreement_no,
        product,
        charge_code,
        price,
        status,
      } = d

      return [
        customer_name,
        ae_customer_id,
        bc_customer_id,
        subscription_id,
        agreement_no,
        product,
        charge_code,
        price,
        status,
      ]
    })

    worksheet.addTable({
      name: 'DepositReport',
      ref: 'A1',
      style: {
        showRowStripes: false,
      },
      columns,
      rows,
    })

    autowidth(worksheet)
  })

  return workbook
}

function autowidth(worksheet, minimalWidth = 10) {
  worksheet.columns.forEach(column => {
    let maxColumnLength = 0
    column.eachCell({ includeEmpty: true }, cell => {
      maxColumnLength = Math.max(
        maxColumnLength,
        minimalWidth,
        cell.value ? cell.value.toString().length : 0
      )
    })
    column.width = maxColumnLength + 2
  })
}

I able to get customer details load in the excel without issue. Like this, enter image description here

As i mention one customer can have multiple subs_month_prices records. So i need to show them in excel where one customer row, with multiple subs_month_prices records in same table.

I’m not sure how to loop subs_month_prices data without duplicating customer data in every row. Can someone help me please.

Chrome Extenion’s Javascript code does not seem to be running on the web page

First time building a chrome extension and generally don’t code with JS or HTML, please bear with me. I am trying to build an extension that specifically looks at the values of a specific website’s HTML elements and, when the conditions are met, executes code that clicks a certain HTML element. I tried in various ways, not able to get any reaction in the devtools console. Nothing seems to be happening. I assume I am misunderstanding something very fundamental here. Any input would be greatly appreciated!

The script only seems to run when I inspect the actual extension popup. In there, in Sources, I can also see the content.js present in the “Page” tab, which is not the case for my example.com webpage.

content.js

console.log("test");

// Function to check if the conditions are met and click the button
function checkAndClick() {
    const clock = document.querySelector("#agentstateui-0 > div > span[role=timer]").innerText;
    const currentState = document.querySelector("#agentstateui-0 > div > div.state-body > div.current-row > span.current-state").textContent.trim();
    const unavailableState = document.querySelector("#agentstateui-0 > div > div.state-body > div.current-row > span.current-out-state").textContent.trim();

    // Get the current local time
    const currentTime = new Date();
    const hours = currentTime.getHours().toString().padStart(2, '0');
    const minutes = currentTime.getMinutes().toString().padStart(2, '0');
    const localTime = `${hours}:${minutes}`;

    if (currentState === "Unavailable" && unavailableState === "Break" && clock === "14:59") {
        const availableBtn = document.querySelector("#agentstateui-0stateList > li:nth-child(1)");
        availableBtn.click();
        console.log("Break ended, clicked Available.");
    }

    if (localTime === "16:59") {
        const testBtn = document.querySelector("#agentstateui-0stateList > li:nth-child(14)");
        testBtn.click();
    }

    console.log("Local Time:", localTime);
}

// Function to run the check periodically
function monitorValues() {
    setInterval(checkAndClick, 500); // Check every 500 milliseconds
}

// Run the monitorValues function when the DOM content is loaded
document.addEventListener('DOMContentLoaded', monitorValues);

manifest.json

{
  "manifest_version": 3,
  "name": "test",
  "version": "1.0",
  "description": "test",
  "host_permissions": [
    "http://*/*",
    "https://*/*"
  ],
  "action": {
    "default_popup": "popup.html"
  },
  "content_scripts": [
    {
      "all_frames": true,
      "matches": ["https://www.example.com/*"],
      "js": ["scripts/content.js"],
      "run_at": "document_idle"
    }
  ],
  "permissions": [               
      "scripting",                
      "storage",                  
      "tabs"               
    ]
}

I tried adding various permissions, using the chrome.scripting to try and inject the javascript but nothing worked.:(

If I manually enter the code to the web page’s console, it works as intended (once, not looping).