Why I cant see console.log() in Call Stack of browser?

I can’t see console.log() in call stack, why?, below sharing images. The code written doesn’t make any sense, it’s just an example

anonymus is the global execution context, and we can see that function getRes is in call stack too (its after executing funcB and funcA)

enter image description here here we can see that global execution context is not finished yet because console.log, but console.log() is function too, why I can’t see it

Components Flickers while Mutation in react-query

There are two components in my Code Public section & Profile Section.
While updating the user profile, Profile Section Flickers/blinks but while updating public section it does not flickers. I can’t understand the reason behind this.

Here is the code bases.

Public Section.

import { useCallback } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Formik, Form } from "formik";
import * as Yup from "yup";
import Switch from "react-switch";
import get from "lodash/get";
import { toast } from "react-toastify";
import Input from "../../../Components/atoms/Input";
import { Button } from "../../../Components/atoms/Button";
import { SPINNER_CONSTANTS } from "../../../Components/molecules/Spinner";
import ErrorToolTip from "../../../Components/molecules/ErrorToolTip";
import { updateUserProfile } from "./userProfile.actions";
import { DEFAULT_VALUES, REGEX, CACHE_KEYS } from "../../../constants";
import { getFormikError } from "../../../Helpers";
import { useUserData } from "../../../hooks";

const { UPDATE_PUBLIC_PROFILE } = SPINNER_CONSTANTS;
const { EMPTY_STRING, EMPTY_OBJECT } = DEFAULT_VALUES;
const { URL } = REGEX;
const { USER_PROFILE } = CACHE_KEYS;

const validationSchema = Yup.object().shape({
  bio: Yup.string().max(100, "Bio should be less than 100 characters"),
  website: Yup.string().matches(URL, "Invalid URL"),
  isPublic: Yup.boolean(),
});

const PublicSection = () => {
  const queryClient = useQueryClient();
  const mutation = useMutation({
    mutationFn: (values) =>
      updateUserProfile({ body: { publicProfile: values } }),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [USER_PROFILE],
      });
      toast.success("Public profile updated successfully");
    },
  });

  const { userData } = useUserData();
  const { isPublic, bio, website } = get(
    userData,
    "publicProfile",
    EMPTY_OBJECT
  );

  const initialValues = {
    bio: bio ?? EMPTY_STRING,
    website: website ?? EMPTY_STRING,
    isPublic: isPublic ?? false,
  };

  const handleSubmit = useCallback(
    (values) => {
      mutation.mutateAsync(values);
    },
    [mutation]
  );

  return (
    <section>
      <div className="py-6">
        <div className="font-semibold text-lg py-6">Public Profile</div>
        <Formik
          validateOnMount
          enableReinitialize
          initialValues={initialValues}
          validationSchema={validationSchema}
          onSubmit={handleSubmit}
        >
          {({
            values,
            touched,
            errors,
            handleChange,
            setFieldValue,
            dirty,
            isValid,
          }) => (
            <Form className="w-full py-1 my-2 grid grid-cols-1 md:grid-cols-2 gap-10">
              <div className="col-span-2 flex gap-2 items-center bg-blue-background-light p-4 rounded-md">
                <Switch
                  onChange={() => setFieldValue("isPublic", !values.isPublic)}
                  checked={values.isPublic}
                  handleDiameter={20}
                  height={20}
                  width={40}
                  uncheckedIcon={false}
                />
                <div>Enable Public Profile</div>
              </div>
              <div className="w-full py-1">
                <Input
                  name="bio"
                  type="text"
                  showLabel
                  labelText="Bio"
                  onChange={handleChange}
                  placeholder="A little blurb about yourself"
                  values={values}
                  className="gap-2"
                  inputClassName="!bg-blue-background-light border border-gray-600 !text-white !text-[14px] !font-normal !focus:outline-pink-primary !active:outline-pink-primary"
                />
                {getFormikError({ name: "bio", touched, errors }) && (
                  <ErrorToolTip message={errors.bio} />
                )}
              </div>
              <div className="w-full py-1">
                <Input
                  name="website"
                  type="text"
                  showLabel
                  labelText="Website"
                  onChange={handleChange}
                  placeholder="Enter your website"
                  values={values}
                  className="gap-2"
                  inputClassName="!bg-blue-background-light border border-gray-600 !text-white !text-[14px] !font-normal !focus:outline-pink-primary !active:outline-pink-primary"
                />
                {getFormikError({ name: "website", touched, errors }) && (
                  <ErrorToolTip message={errors.website} />
                )}
              </div>
              <Button
                title="Update Profile"
                className="!w-fit !bg-pink-primary !px-6 !text-sm !h-fit !font-normal"
                spinnerName={UPDATE_PUBLIC_PROFILE}
                isSpinnerActive={mutation.isPending}
                type="submit"
                isDisabled={!isValid || !dirty}
                onClick={() => handleSubmit(values)}
              />
            </Form>
          )}
        </Formik>
      </div>
    </section>
  );
};

export default PublicSection;

Profile Section

import { useCallback, useRef } from "react";
import { useDispatch } from "react-redux";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Formik, Form } from "formik";
import * as Yup from "yup";
import { toast } from "react-toastify";
import { IoCheckmarkDoneOutline, IoAdd } from "react-icons/io5";
import { updateUserProfile } from "./userProfile.actions";
import Input from "../../../Components/atoms/Input";
import { Button } from "../../../Components/atoms/Button";
import ErrorToolTip from "../../../Components/molecules/ErrorToolTip";
import { toggleSideBar } from "../../../Components/organisms/SideBar";
import { SIDEBAR_CONSTANTS } from "../../../Components/organisms/AppSideBars";
import { createFormDataFromObject, getFormikError } from "../../../Helpers";
import { DEFAULT_VALUES, CACHE_KEYS } from "../../../constants";
import { useUserData } from "../../../hooks";

const { ACCOUNT_VERIFICATION } = SIDEBAR_CONSTANTS;
const { EMPTY_STRING, ZERO } = DEFAULT_VALUES;
const { USER_PROFILE } = CACHE_KEYS;

const validationSchema = Yup.object().shape({
  name: Yup.string().required("Email is required"),
});

const ProfileSection = () => {
  const dispatch = useDispatch();
  const queryClient = useQueryClient();

  const mutation = useMutation({
    mutationFn: (values) => updateUserProfile({ body: values }),
    onSuccess: () => {
      queryClient.invalidateQueries({
        queryKey: [USER_PROFILE],
      });
      toast.success("Profile updated successfully");
    },
  });

  const { userData } = useUserData();
  const fileInputRef = useRef();
  const {
    name = EMPTY_STRING,
    email = EMPTY_STRING,
    avatar = {},
    isEmailVerified,
    phoneNumber = EMPTY_STRING,
  } = userData || {};

  const initialValues = {
    name,
    email,
    photo: avatar?.secure_url ?? EMPTY_STRING,
    phoneNumber,
  };

  const handleSubmit = useCallback(
    (values) => {
      const data = createFormDataFromObject(values);
      mutation.mutateAsync(data);
    },
    [mutation]
  );

  const handlePhotoSelect = () => fileInputRef.current.click();

  const openAccountVerificationSideBar = useCallback(
    () =>
      dispatch(
        toggleSideBar({
          showSideBar: true,
          sideBarConstant: ACCOUNT_VERIFICATION,
        })
      ),
    [dispatch]
  );

  return (
    <div className="py-6">
      <div className="font-semibold text-lg py-6">Profile Information</div>
      <Formik
        validateOnMount
        enableReinitialize
        initialValues={initialValues}
        validationSchema={validationSchema}
        onSubmit={handleSubmit}
      >
        {({ values, touched, errors, handleChange, setFieldValue, dirty }) => (
          <div>
            <Form className="w-full py-1 my-2 grid grid-cols-1 md:grid-cols-2 gap-10">
              <div className="w-full py-1">
                <Input
                  name="name"
                  type="text"
                  showLabel
                  labelText={"Name"}
                  onChange={handleChange}
                  placeholder="Enter your name"
                  values={values}
                  className="gap-2"
                  inputClassName="!bg-blue-background-light border border-gray-600 !text-white !text-[14px] !font-normal !focus:outline-pink-primary !active:outline-pink-primary"
                />
                {getFormikError({ name: "name", touched, errors }) && (
                  <ErrorToolTip message={errors.name} />
                )}
              </div>
              <div>
                <input
                  ref={fileInputRef}
                  className="hidden"
                  name="photo"
                  onChange={(e) => {
                    setFieldValue("photo", e.target.files[ZERO]);
                    e.target.files[ZERO] &&
                      setFieldValue("isPhotoChanged", true);
                  }}
                  type="file"
                  accept="image/png, image/jpg, image/jpeg"
                />
                <label htmlFor="photo" className="text-[12px]">
                  Profile Picture
                </label>
                <div
                  className="border-2 w-16 h-16 my-3 rounded-full overflow-hidden cursor-pointer"
                  onClick={handlePhotoSelect}
                >
                  <img
                    src={
                      values.isPhotoChanged
                        ? window.URL.createObjectURL(values.photo)
                        : values.photo
                    }
                    className="w-16 h-16 rounded-full"
                    alt="user-default"
                  />
                </div>
              </div>
              <div className="w-full py-1">
                <Input
                  name="phoneNumber"
                  type="text"
                  showLabel
                  labelText="Phone Number"
                  onChange={handleChange}
                  placeholder="Enter your phone number"
                  values={values}
                  className="gap-2"
                  inputClassName="!bg-blue-background-light border border-gray-600 !text-white !text-[14px]"
                  disabled
                  SuffixElement={
                    !values.phoneNumber ? (
                      <IoAdd
                        className="cursor-pointer"
                        onClick={openAccountVerificationSideBar}
                      />
                    ) : (
                      <IoCheckmarkDoneOutline className="text-green-500" />
                    )
                  }
                />
              </div>
              <div className="w-full py-1">
                <Input
                  name="email"
                  type="email"
                  showLabel
                  labelText="Email"
                  onChange={handleChange}
                  placeholder="Enter your email"
                  values={values}
                  className="gap-2"
                  inputClassName="!bg-blue-background-light border border-gray-600 !text-white !text-[14px]"
                  disabled
                  SuffixElement={
                    isEmailVerified && (
                      <IoCheckmarkDoneOutline className="text-green-500" />
                    )
                  }
                />
              </div>
            </Form>
            <Button
              title="Update Info"
              className="!w-fit !bg-pink-primary !px-6 !text-sm !h-fit !font-normal !mt-6"
              type="submit"
              isDisabled={!dirty}
              onClick={() => handleSubmit(values)}
              isSpinnerActive={mutation.isPending}
            />
          </div>
        )}
      </Formik>
    </div>
  );
};

export default ProfileSection;

Code for hook for use-UseData

import { useCallback } from "react";
import { useQuery } from "@tanstack/react-query";
import { CACHE_KEYS } from "../constants";
import { fetchUserProfile } from "../Screens/User/UserProfile";

const { USER_PROFILE, IS_AUTHENTICATED } = CACHE_KEYS;

const useUserData = () => {
  const isAuthenticated = Boolean(localStorage.getItem(IS_AUTHENTICATED));

  const { data, refetch, isFetching } = useQuery({
    queryKey: [USER_PROFILE],
    queryFn: ({ signal }) => fetchUserProfile({ signal }),
    enabled: isAuthenticated,
    refetchOnWindowFocus: true,
    staleTime: Infinity,
  });

  const refetchUserProfile = useCallback(() => refetch(), [refetch]);

  return {
    userData: data?.data,
    refetchUserProfile,
    isLoading: isFetching,
    isAuthenticated,
  };
};

export default useUserData;

I am expecting a reason behind the flickering issues, and if I am writing somethig wrong, Please let me know.

What is the difference between slice and splice

I’m seeking information about a versatile JavaScript function applicable to both strings and arrays. This function takes two parameters: the JavaScript index and another parameter. Could someone provide an explanation along with a sample code snippet, highlighting the proper arrangement of these arguments? Thanks

What is the difference between island and vanilla JS?

From Astro Islands | Docs:

In Astro, an “island” refers to any interactive UI component on the page. Think of an island as an interactive widget floating in a sea of otherwise static, lightweight, server-rendered HTML.

I don’t see how is this be any different to vanilla JS. In both cases, the server first serve the HTML file, then the users wait for the JS files to load. Or is the concept only useful when you want to use a framework? Is this a way for frameworks to say “Hey, I’m the closest thing to vanilla JS that you can find, without sacrifice your developer experience”?

using the select2 javascript library

Manage mouse hover and automatic option selection

$(document).on('mouseenter', '.select2-container', function() { 
   $(this).prev("select").select2("open"); 
});
$(document).on('mouseleave', '.select2-container', function() {
    $(this).prev("select").select2("close");
});

There is automatic scrolling of the list but it disappears immediately so that I cannot select

How to change the local domain in next.js application?

I want to change the local (development) domain in my Next.js 14 application.
Instead of having something like: “http://localhost:4200” I want to have something like: “https://dev.mydomain.com”.

I’m using next.js 14 with the new app router (If it’s relevant for some reason).
Also, I’m using nx.dev for managing my repo.

I don’t see anything related to that in the docs so I would be happy to have some help here.
Thanks.

ERR_NETWORK_IO_SUSPENDED causing infinite requests

So I have the following code which aims to automatically synchronize everything with a server.

This function is called once upon opening the website (logged in) or once the user logs in

static async sync(): Promise<void> {
    while (this.active) {
        try {
            await SomeClass.sync()
        }
        catch (error) {
            console.error(error)
            this.active = false;
        }
    }
}

NOTE: SomeClass.sync() is a different method! it’s not recursive

SomeClass.sync() takes up to 30s to respond but it can respond immediately when a change occurs on the server; in that case it responds quicker and I make the next SomeClass.sync() call as soo as possible.

This works fine until the browser tab is inactive for too long or the PC goes to sleep mode. Because after opening the tab again I saw that thousands of sync requests were made and the followed error is seen in the command line (thousands of times) but the catch block is never entered.

GET https://matrix-client.matrix.org/_matrix/client/v3/sync?filter=6&full_state=false&set_presence=online&timeout=30000&since=s4618108627_757284974_5471239_2578824090_2744102759_5162233_1222064987_9519760537_0_225843 net::ERR_NETWORK_IO_SUSPENDED

The main issue is that after opening the browser tab the calls resume correctly but everything is kinda laggy because tens of thousand of calls were made in that time (every 1-2ms).

I tried catching and logging the error in different ways but it was never caught. I also tried throwing an Error if await someClass.sync() doesn’t resolve within X seconds but this didn’t work either.

How can I auto log cypress test name?

I’d like to be able to tell cypress to log each test name.

I know I can put inside each spec’s beforeEach() the following line:

cy.log(‘Executing beforeEach() for: ' + Cypress.currentTest.title)

But I’d don’t like the need to remember to add it to each beforeEach() hook implementation.

Is there a cleaner way to achieve this goal?

Offscreen Canvas in Web Worker not Updating when Editing Rendering Context

context: I am using a mapping library called openglobus to render a 3d planet. Openglobus has a tile layer, where you can give a function that generates tiles, that function can return canvasses. So what I made is a function that generates these canvasses to get rendered as a map layer on that globe. To keep things performant, this function is asynchronous and calls upon a webworker to do the actual tile generation. So the canvas is made in the main thread by the tile generator function. Then the canvas transfers its control to offscreen. next the webworker gets on it with all required parameters. And when the web worker finishes, the canvas is applied to the globe.

Tile generator function looks like this (WM stands for Worker Manager that distributes requests over the multiple workers):

export default function BaseLayer(WM) {
  return new layer.CanvasTiles(`cnv`, {
    isBaseLayer: true,
    drawTile: function (material, applyCanvas) {
      const { tileZoom, tileX, tileY } = material.segment;
      const extent = material.segment.getExtentLonLat();
      const res = 700;

      const cnv = document.createElement("canvas");
      cnv.width = res;
      cnv.height = res;

      const offscreen = cnv.transferControlToOffscreen();

      WM.makeBaseTile({
        extent,
        tileX,
        tileY,
        tileZoom,
        res,
        offscreen,
      }).then(_ => applyCanvas(cnv));
    },
  });
}

problem: When I coded it this way, I had issues with some tiles not loading. Some of them do, but some of them don’t. It happens on both Chrome and Firefox so I don’t think it is related to this post, or this existing Chrome bug (that bug also is marked as fixed already).

What it shouldnt look like

The issue seems to be most prevalent on complexer tiles that take longer to generate. But it is all asynchronous so I don’t understand why that could be the reason.

I did find a fix however. That’s why I don’t think this is an issue with the openglobus library, but with the way offscreencanvasses work. By using the commit() function on the OffscreenCanvasRenderingContext2D at the end of the worker’s process, I get a perfectly working example:

What it should look like

However this commit function is only available for Safari en Firefox browsers, and not for Chrome(ium) based browsers. Does anyone better understand why this happens without the commit function, or how this can be fixed in Chrome? I have been looking for a while already but there doesn’t seem to be an equivalent to the commit function.

Why does the equality operator not give the expected ‘true’ result in this context? (javascript) [duplicate]

This function is supposed to produce an array of random points on an axis and keep the last point in the array as a final ‘choice’. The function is called repeatedly by user action and the function is supposed to ensure that any final choice point is not repeated in future function calls.

For an unknown reason the equality logic is not working as expected. I tried ‘.includes()’ originally to check the pastChoices array and it didn’t catch repetitions. I created the console.log series shown below to verify that the equality operator is not working in this context.

1  import random from "lodash/random.js";
2
3  let pastChoices = [];
4
5  export function compAttack() {
6   let choiceArray = [];
7   let choice;
8   console.log(pastChoices);
9   for (let i = 0; i <= 25; i++) {
10      let y = random(1, 10);
11      let x = random(1, 10);
12      choiceArray.push(`${y},${x}`);
13      if (i != 25) continue;
14      choice = choiceArray[choiceArray.length - 1].split(",");
15      pastChoices.forEach((x) => {
16          console.log(x);
17          console.log(choice);
18          console.log(choice == x);
19      });
20  }
21  pastChoices.push(choice);
22 }

Console Output:

02:23:25.786 compAttack.js:16 (2) ['7', '2']
02:23:25.787 compAttack.js:17 (2) ['9', '10']
02:23:25.788 compAttack.js:18 false
02:23:25.788 compAttack.js:16 (2) ['9', '10']
02:23:25.789 compAttack.js:17 (2) ['9', '10']
02:23:25.789 compAttack.js:18 false
02:23:25.789 compAttack.js:16 (2) ['6', '2']
02:23:25.789 compAttack.js:17 (2) ['9', '10']
02:23:25.789 compAttack.js:18 false

I’ve been able to come up with another way to achieve my end goal (not using equality) but I’m curious as to why this is happening?

Is it a runtime issue? Or more likely, is it a me issue?

I pulled the function out of my application (refactored it a little) and ran it in a stand alone file to see if the behavior would be consistent and lo and behold.

I’m expecting “repeat” to print to the console but it doesn’t.

import random from "lodash/random.js";

let pastChoices = [];

export function compAttack() {
    let choiceArray = [];
    let choice;
    console.log(pastChoices);
    for (let i = 0; i <= 25; i++) {
        let y = random(1, 10);
        let x = random(1, 10);
        choiceArray.push(`${y},${x}`);
        if (i != 25) continue;
        choice = choiceArray[choiceArray.length - 1].split(",");
        if (pastChoices.includes(choice)) {
            console.log("repeat");
        }
    }
    pastChoices.push(choice);
}

for (let i = 0; i < 50; i++) {
    compAttack();
}

Console Output – This is the finally array after the last call and there are repetitions but ‘repeat’ never printed to console at any point.

[
  [ '3', '5' ],  [ '8', '2' ],  =>[ '4', '2' ],
  [ '8', '9' ],  [ '9', '6' ],  [ '10', '10' ],
  [ '9', '9' ],  [ '2', '4' ],  [ '4', '5' ],
  [ '6', '9' ],  [ '4', '10' ], [ '7', '6' ],
  =>[ '4', '2' ],[ '10', '4' ], [ '8', '5' ],
  [ '5', '1' ],  [ '9', '1' ],  [ '5', '3' ],
  [ '4', '8' ],  [ '5', '5' ],  [ '3', '8' ],
  [ '8', '2' ],  [ '7', '9' ],  [ '6', '7' ],
  [ '1', '1' ],  [ '7', '9' ],  [ '5', '6' ],
  [ '6', '4' ],  [ '8', '1' ],  [ '6', '3' ],
  [ '1', '3' ],  [ '8', '8' ],  [ '8', '4' ],
  [ '1', '5' ],  [ '3', '2' ],  [ '6', '3' ],
  [ '2', '10' ], [ '5', '7' ],  [ '2', '1' ],
  [ '7', '1' ],  [ '1', '9' ],  [ '5', '8' ],
  [ '5', '2' ],  [ '10', '6' ], [ '2', '6' ],
  [ '6', '2' ],  [ '1', '2' ],  [ '4', '2' ],
  [ '8', '5' ]
]

convert data into queryset in django

I have data retrieved from databases using cursor in django, as the data is from more than one table that has a relationship. I want to convert the data to a quertset in order to use the annotite and order_by and values

I tried to use the function list_to_queryset() from the convert_to_queryset library, but this function converts data into a queryset for only one Model, and I want to convert data, even if it is more than one Model.

Can’t interact with smart contract which deals with encrypted values using fhevm library

I have created a contract in truffle suite and deployed it successfully. I have used the TFHE library of fhevm by Zama. I have taken an encrypted variable and unencrypted variable and made a function for performing addition. Here is the contract:

// SPDX-License-Identifier: BSD-3-Clause-Clear
pragma solidity ^0.8.0;

import "../fhevm/lib/TFHE.sol";

contract AddValue {
    function add(euint32 a, uint32 b) public view returns (euint32) {
        return TFHE.add(a, b);
    }
}

This contract is placed in contracts folder which gets generated after running the command truffle init
After deployment and instantiating when i am trying to call the add() function and pass the parameters then it is showing an error:

Uncaught Error: VM Exception while processing transaction: revert
    at evalmachine.<anonymous>:1:20
    at evalmachine.<anonymous>:2:48
    at sigintHandlersWrap (node:vm:258:12)
    at Script.runInContext (node:vm:131:14)
    at runScript (C:UsersRonita AdhikariAppDataRoamingnpmnode_modulestrufflebuildwebpack:packagescorelibconsole.js:505:1)
    at Console.interpret (C:UsersRonita AdhikariAppDataRoamingnpmnode_modulestrufflebuildwebpack:packagescorelibconsole.js:520:1)
    at bound (node:domain:432:15)
    at REPLServer.runBound [as eval] (node:domain:443:12)
    at REPLServer.onLine (node:repl:929:10)
    at REPLServer.emit (node:events:514:28)
    at REPLServer.emit (node:domain:488:12)
    at REPLServer.[_onLine] [as _onLine] (node:internal/readline/interface:416:12)
    at REPLServer.[_line] [as _line] (node:internal/readline/interface:887:18)
    at REPLServer.[_ttyWrite] [as _ttyWrite] (node:internal/readline/interface:1265:22)
    at REPLServer.self._ttyWrite (node:repl:1024:9)
    at ReadStream.onkeypress (node:internal/readline/interface:264:20)
    at ReadStream.emit (node:events:514:28)
    at ReadStream.emit (node:domain:488:12)
    at emitKeys (node:internal/readline/utils:371:14)
    at emitKeys.next (<anonymous>) {
  code: -32000,
  data: '0x',
  hijackedStack: 'Error: VM Exception while processing transaction: revertn' +
    '    at C:\Users\Ronita Adhikari\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\provider\wrapper.js:25:1n' +
    '    at C:\Users\Ronita Adhikari\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\provider\wrapper.js:166:1n' +
    '    at C:\Users\Ronita Adhikari\AppData\Roaming\npm\node_modules\truffle\build\webpack:\node_modules\web3-providers-http\lib\index.js:127:1n' +
    '    at processTicksAndRejections (node:internal/process/task_queues:95:5)'
} ```

Please point out the problem and probably recommend me a solution. All I want to do is take one encrypted value and the other unencrypted and return the sum in encrypted format.

My react project’s javascript isn’t working

I am creating a project in reactjs. But the moment I do “npm start” my firefox developer edition browser gives me an error (Note that I didn’t do any changes to any files since I run it for the first time).
Error in firefox (developer version)

So, I did everything from deleting and creating the project to updating npm to re-installing node.js but nothing worked. Then I switched to chrome and it did not gave me any error, which made me come to a conclusion that it was some kind of browser issue. After creating some elements in my website, I was adding a javascript function to my nav. It didn’t work plus it made my browser hang and made the page unresponsive. Needless to say, the browser wasn’t the issue i suppose. Chrome just didn’t give me any error while I was using just html and css but now it is hanging now that I have applied javascript. I again switched my browser to Edge and same hanging issue. Please tell me whats causing this and how to solve it?
This is what the console in firefox shows even if I first run the project without doing any changes to my project

Textarea not updating in my Markdown Previewer

I’ve been working on this Markdown Previewer to improve my skills in JavaScript and React and I’ve run into an issue I can’t solve. I don’t know if I’ve just been staring at it too long or what.

Everything loads properly, the only issue is that when I try to type something into the textarea, it won’t let me change anything in it. It isn’t set to read only, so I’m really unsure as to what it is doing this.

Component

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      markdown: initialMarkdown
    };
    this.handleChange(this.handleChange.bind(this));
  }

  handleChange(event) {
    try {
      this.setState({
        markdown: event.target.value
      });
    } catch (e) {}
  }

  render() {
    return (
      <div>
        <div className="input">
          <div className="header">Editor</div>
          <textarea
            id="editor"
            value={this.state.markdown}
            onChange={this.handleChange}
          ></textarea>
        </div>
        <div className="output">
          <div className="header">Preview</div>
          <div
            id="preview"
            dangerouslySetInnerHTML={{ __html: marked(this.state.markdown) }}
          ></div>
        </div>
      </div>
    );
  }
}

//Rendering to HTML
ReactDOM.render(<App />, document.getElementById("app"));

I’ve scoured a few different threads and subreddits and what not, but I have found nothing to solve my issue. Anybody got any ideas?

Google reCAPTCHA Enterprise not Blocking Automated Requests with Puppeteer

I have built a website that utilizes Google reCAPTCHA Enterprise to protect against automated bot attacks. However, I have encountered a situation where my automation script, developed using Puppeteer, is able to successfully bypass the reCAPTCHA challenge and proceed with form submissions. Surprisingly, the reCAPTCHA score I receive is 0.8, indicating a good score. I am perplexed as to why my script is not being blocked as expected.

here is how my backend check the recaptcha token:

async function createAssessment({ projectID, recaptchaKey, token, recaptchaAction }) {
const client = new RecaptchaEnterpriseServiceClient();
const projectPath = client.projectPath(projectID);
const target_event = {
    'token': token,
    siteKey: recaptchaKey
};

const request = {
    assessment: {
        event: target_event
    },
    parent: projectPath,
};

console.log('Creating assessment...');
const [response] = await client.createAssessment(request);
console.log('Assessment created.');

if (!response.tokenProperties.valid) {
    console.log(`The CreateAssessment call failed because the token was: ${response.tokenProperties.invalidReason}`);
    return { score: null, failReason: response.tokenProperties.invalidReason };
}

if (response.tokenProperties.action === recaptchaAction) {
    console.log(`The reCAPTCHA score is: ${response.riskAnalysis.score}`);
    response.riskAnalysis.reasons.forEach((reason) => {
        console.log(reason);
    });

    return { score: response.riskAnalysis.score, failReason: null };
} else {
    console.log("The action attribute in your reCAPTCHA tag does not match the action you are expecting to score");
    return { score: null, failReason: "The action attribute in your reCAPTCHA tag does not match the action you are expecting to score" };
}

from automation script it is like this:

const puppeteer = require('puppeteer');
async function run() {
const browser = await puppeteer.launch({ headless: true });
const page = await browser.newPage();
for (let i = 1; i <= 50; i++) {
    try {
        console.log(`Processing iteration ${i}`);

        // Navigate to the website
        console.log(`Iteration ${i}: Navigating to the website`);
        await page.goto('https://my-domain.com/');

        // Enter the username
        console.log(`Iteration ${i}: Entering the username`);
        await page.type('input[name="login"]', `autotester ${i}`);

        // Enter the password
        console.log(`Iteration ${i}: Entering the password`);
        await page.type('input[name="password"]', 'autotesterpassword');

        // Click the submit button
        console.log(`Iteration ${i}: Clicking the submit button`);
        await page.click('button[type="submit"]');

        // Wait for the page to load after submitting the form
        console.log(`Iteration ${i}: Waiting for the page to load`);
        await page.waitForSelector('#loadingDialog', { hidden: true });

        // Take a screenshot or perform further actions if needed
        console.log(`Iteration ${i}: Taking a screenshot`);
        await page.screenshot({ path: `screenshot_${i}.png` });

        console.log(`Iteration ${i} completed successfully`);
    } catch (error) {
        console.error(`Error occurred in iteration ${i}:`, error);
    }
}

// Close the browser
await browser.close();}run().catch(error => console.error(error));

I would like to seek the community’s expertise in understanding why Google reCAPTCHA Enterprise might fail to block automated requests in certain scenarios, especially when using Puppeteer.

Any insights or guidance on this issue would be greatly appreciated. Thank you!