SIP.js Audio Lost After Network Change & Reconnect – Works in JsSIP

I’m building a SIP/WebRTC app with SIP.js, and I’ve implemented a reconnection and renegotiation flow for when the user changes networks mid-call (e.g., Wi-Fi → Mobile Data). However, I’m facing a critical issue:

Problem

  • After a network change:

  • SIP.js reconnects successfully.

  • Re-INVITE is accepted.

  • The session remains active (no errors).

  • But no audio is heard on either side.

What Works Perfectly in JsSIP
In JsSIP, this same logic works flawlessly. Audio resumes correctly after ICE restarts.

JsSIP Code (Working)

 const renegotiate = (session: JsSIP.RTCSession): Promise<void> => {
    return new Promise((resolve, reject) => {
    if (!session) return reject("No session to renegotiate");
    console.info("Starting renegotiation with ICE restart...");
session.renegotiate(
          {
            rtcOfferConstraints: {
          offerToReceiveAudio: 1,
             offerToReceiveVideo: 0,
            iceRestart: true,
         },
       },
      () => resolve(),
      (err) => reject(err)
    );
  });
};

In peerconnection.oniceconnectionstatechange, I call renegotiate() if the ICE connection is “disconnected” or “failed”. After this, the audio resumes fine on both ends.

SIP.js Code (Fails – No Audio)
In SIP.js, I do the following:

  1. Manually replace audio track:

       const localStream = sdh.localMediaStream;
        if (localStream) {
        const audioTrack = localStream.getAudioTracks()[0];
        if (audioTrack) {
           pc.getSenders().forEach(sender => {
            if (sender.track?.kind === 'audio') {
              sender.replaceTrack(audioTrack);
            }
          });
         }
        }
    
  2. Restart ICE with re-INVITE:

       const offer = await pc.createOffer({ iceRestart: true });
        await pc.setLocalDescription(offer);
    
         await session.invite({
          requestDelegate: {
          onAccept: response => {
            console.log('Re-INVITE accepted');
             setupRemoteMedia(session, false); 
           },
           onReject: () => {
           console.warn('Re-INVITE rejected');
           }
        },
        sessionDescriptionHandlerOptions: {
          constraints: { audio: true, video: false }
        }
       });
    

The re-INVITE is accepted, signaling and ICE state are okay — but no audio is received or sent.

Notes

  • I’ve confirmed peerConnection.connectionState === “connected”.

  • remoteAudioEl.srcObject is correctly set.

  • Audio was working before the network change.

  • STUN server is stun:stun.l.google.com:19302.

  • Permissions are granted; media devices are valid.

  • I’ve tried both replacing audio tracks manually and using a fresh stream.

Versions

  • SIP.js: ^0.21.2

  • JsSIP: 3.10.0

  • Browsers: Chrome (latest), Edge

  • App: Next.js + WebRTC

What I Want to Know

  • Any known workarounds or best practices for handling network change + audio recovery in SIP.js?
Library Reconnect Audio Restored
JsSIP Yes Yes
SIP.js Yes No

Why is a required field (userId) undefined in Mongoose even though it exists in the database?

I’m using Mongoose with a MongoDB collection where the userId field is defined as required in my schema like this –

userId: {
  type: String,
  required: true,
  ref: 'user'
}

When I fetch document using findById():

const event = await Model.findById(eventId);
console.log(event.userId); // prints: undefined

But When I check the actual document in the database (via monogoDB compass) then userId is clearly visible and correctly set with (ObjectId)

This causes Mongoose.save() to throw a validation error:
Path “userId” is required.

Even trying console.log(event) or event.toObject() doesn’t show userId.

but to fix this I had to manually assign it everytime when I’m updating –

if (!event.userId) {
  event.userId = userId;
}

But this feels like a hack.

version are here –

“mongodb”: “5.1.0”,
“mongoose”: “6.5.5”,

I was trying to update a document in my MongoDB collection using Mongoose. The document has a userId field that’s marked as required in the schema.

I fetched the document using findOne(), findById() and updated one of its array fields. But when I called .save(), it threw this error:

calendar-events validation failed: userId: Path userId is required.

At the same time I also get this strange error –

Cannot read properties of undefined (reading ‘options’)

This confused me because:

  1. The userId field definitely exists in the MongoDB document (I checked via Compass and raw queries).
  2. I’m not using .lean().
  3. I’m not excluding userId via .select().
  4. And I don’t have anything called options in my schema or the data I’m working with.

Why is TypeScript using 100% CPU?

I don’t know why but my TypeScript server is using all of my CPU and then it crashes. My guess is it’s also handling files inside the node_modules folder, because when I delete the node_modules folder. the npx tsc --listFiles command works fine. But with the node_modules folder it gets stuck using all of my CPU then it throws javascript heap out of memory error.

Check this output

napstar@KHAN-PC:~/dev/imgDrive$ tsc --listFiles

<--- Last few GCs --->

[11058:0x2be67000]   108760 ms: Scavenge (interleaved) 2042.7 (2083.8) -> 2041.0 (2087.8) MB, pooled: 0 MB, 3.51 / 0.00 ms  (average mu = 0.088, current mu = 0.011) allocation failure;
[11058:0x2be67000]   109124 ms: Mark-Compact (reduce) 2044.9 (2088.3) -> 2043.0 (2083.1) MB, pooled: 0 MB, 288.53 / 0.00 ms  (+ 15.9 ms in 0 steps since start of marking, biggest step 0.0 ms, walltime since start of marking 325 ms) (average mu = 0.210, cu

<--- JS stacktrace --->

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
----- Native stack trace -----

 1: 0xe16044 node::OOMErrorHandler(char const*, v8::OOMDetails const&) [node]
 2: 0x11e0dd0 v8::Utils::ReportOOMFailure(v8::internal::Isolate*, char const*, v8::OOMDetails const&) [node]
 3: 0x11e10a7 v8::internal::V8::FatalProcessOutOfMemory(v8::internal::Isolate*, char const*, v8::OOMDetails const&) [node]
 4: 0x140e985  [node]
 5: 0x140e9b3  [node]
 6: 0x1427a8a  [node]
 7: 0x142ac58  [node]
 8: 0x1c90921  [node]
Aborted (core dumped)
napstar@KHAN-PC:~/dev/imgDrive$

For context I am using pnpm as package manager, my app is in Next.js, below is my tsconfig.json

// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2017",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": [
        "./*"
      ]
    }
  },
  "include": [
    "**/*.ts",
    "**/*.tsx",
    ".next/types/**/*.ts",
    "next-env.d.ts",
    "build/types/**/*.ts"
  ],
  "exclude": [
    "node_modules",
    "build",
    ".next"
  ]
}

I enabled server logs for TypeScript in VS Code, and this what I got

napstar@KHAN-PC:~/dev/imgDrive$ cat /home/napstar/.vscode-server/data/logs/20250717T114015/exthost2/vscode.typescript-language-features/tsserver-log-pKGsVY/tsserver.log
Info 0    [12:08:54.048] Starting TS Server
Info 1    [12:08:54.048] Version: 5.8.3
Info 2    [12:08:54.048] Arguments: /home/napstar/.vscode-server/bin/7adae6a56e34cb64d08899664b814cf620465925/node /home/napstar/dev/imgDrive/node_modules/typescript/lib/tsserver.js --useInferredProjectPerProjectRoot --disableAutomaticTypingAcquisition --cancellationPipeName /tmp/vscode-typescript1000/b2b07718e2cd64fe9b66/tscancellation-26973b6f1cbad88ad3e1.tmp* --logVerbosity normal --logFile /home/napstar/.vscode-server/data/logs/20250717T114015/exthost2/vscode.typescript-language-features/tsserver-log-pKGsVY/tsserver.log --traceDirectory "/home/napstar/.vscode-server/data/logs/20250717T114015/exthost2/vscode.typescript-language-features/tsserver-log-jtTbtJ" --locale en --noGetErrOnBackgroundUpdate --canUseWatchEvents --validateDefaultNpmLocation --useNodeIpc
Info 3    [12:08:54.048] Platform: linux NodeVersion: v22.15.1 CaseSensitive: true
Info 4    [12:08:54.048] ServerMode: undefined hasUnknownServerMode: undefined
Info 5    [12:08:54.054] currentDirectory:: /mnt/c/Users/zohai/AppData/Local/Programs/Microsoft VS Code useCaseSensitiveFileNames:: true
Info 6    [12:08:54.054] libs Location:: /home/napstar/dev/imgDrive/node_modules/.pnpm/[email protected]/node_modules/typescript/lib
Info 7    [12:08:54.054] globalTypingsCacheLocation:: undefined
Info 8    [12:08:54.057] Host information vscode
Info 9    [12:08:54.059] getConfigFileNameForFile:: File: /home/napstar/dev/imgDrive/app/account/images/edit-dialog-control.tsx ProjectRootPath: /home/napstar/dev/imgDrive:: Result: /home/napstar/dev/imgDrive/tsconfig.json
Info 10   [12:08:54.060] Creating ConfiguredProject: /home/napstar/dev/imgDrive/tsconfig.json, currentDirectory: /home/napstar/dev/imgDrive
Info 11   [12:08:54.094] Config: /home/napstar/dev/imgDrive/tsconfig.json : {
 "rootNames": [
  "/home/napstar/dev/imgDrive/actions.ts",
  "/home/napstar/dev/imgDrive/auth.ts",
  "/home/napstar/dev/imgDrive/drizzle.config.ts",
  "/home/napstar/dev/imgDrive/jest.config.ts",
  "/home/napstar/dev/imgDrive/jest.polyfill.ts",
  "/home/napstar/dev/imgDrive/jest.setup.ts",
  "/home/napstar/dev/imgDrive/middleware.ts",
  "/home/napstar/dev/imgDrive/next-env.d.ts",
  "/home/napstar/dev/imgDrive/next.config.ts",
  "/home/napstar/dev/imgDrive/__mocks__/server.ts",
  "/home/napstar/dev/imgDrive/app/api/auth/[...nextauth]/route.ts",
  "/home/napstar/dev/imgDrive/app/api/images/handle-request.ts",
  "/home/napstar/dev/imgDrive/app/api/images/route.ts",
  "/home/napstar/dev/imgDrive/app/api/images/[id]/route.ts",
  "/home/napstar/dev/imgDrive/app/api/images/__tests__/handle-requests.test.ts",
  "/home/napstar/dev/imgDrive/app/api/images/__tests__/route.test.ts",
  "/home/napstar/dev/imgDrive/app/i/[id]/route.ts",
  "/home/napstar/dev/imgDrive/config/index.ts",
  "/home/napstar/dev/imgDrive/hooks/use-drive-uploader.ts",
  "/home/napstar/dev/imgDrive/hooks/use-mobile.ts",
  "/home/napstar/dev/imgDrive/hooks/__tests__/use-drive-uploader.test.ts",
  "/home/napstar/dev/imgDrive/lib/drive.ts",
  "/home/napstar/dev/imgDrive/lib/helpers.ts",
  "/home/napstar/dev/imgDrive/lib/rate-limiter.ts",
  "/home/napstar/dev/imgDrive/lib/redis.ts",
  "/home/napstar/dev/imgDrive/lib/utils.ts",
  "/home/napstar/dev/imgDrive/lib/db/index.ts",
  "/home/napstar/dev/imgDrive/lib/db/schema.ts",
  "/home/napstar/dev/imgDrive/lib/db/repositories/accounts.ts",
  "/home/napstar/dev/imgDrive/lib/db/repositories/api-key-logs.ts",
  "/home/napstar/dev/imgDrive/lib/db/repositories/api-keys.ts",
  "/home/napstar/dev/imgDrive/lib/db/repositories/images.ts",
  "/home/napstar/dev/imgDrive/lib/middleware/authenticate-api-key.ts",
  "/home/napstar/dev/imgDrive/lib/schemas/forms.ts",
  "/home/napstar/dev/imgDrive/types/index.ts",
  "/home/napstar/dev/imgDrive/types/next-auth.d.ts",
  "/home/napstar/dev/imgDrive/app/layout.tsx",
  "/home/napstar/dev/imgDrive/app/not-found.tsx",
  "/home/napstar/dev/imgDrive/app/page.tsx",
  "/home/napstar/dev/imgDrive/app/account/layout.tsx",
  "/home/napstar/dev/imgDrive/app/account/not-found.tsx",
  "/home/napstar/dev/imgDrive/app/account/page.tsx",
  "/home/napstar/dev/imgDrive/app/account/(upload)/layout.tsx",
  "/home/napstar/dev/imgDrive/app/account/(upload)/upload/images-input.tsx",
  "/home/napstar/dev/imgDrive/app/account/(upload)/upload/images-list.tsx",
  "/home/napstar/dev/imgDrive/app/account/(upload)/upload/page.tsx",
  "/home/napstar/dev/imgDrive/app/account/[...slug]/page.tsx",
  "/home/napstar/dev/imgDrive/app/account/api-keys/columns.tsx",
  "/home/napstar/dev/imgDrive/app/account/api-keys/copy-api-key-dialog.tsx",
  "/home/napstar/dev/imgDrive/app/account/api-keys/create-api-key-dialog.tsx",
  "/home/napstar/dev/imgDrive/app/account/api-keys/data-table.tsx",
  "/home/napstar/dev/imgDrive/app/account/api-keys/page.tsx",
  "/home/napstar/dev/imgDrive/app/account/api-keys/revoke-api-key-alert.tsx",
  "/home/napstar/dev/imgDrive/app/account/images/delete-alert.tsx",
  "/home/napstar/dev/imgDrive/app/account/images/edit-dialog-control.tsx",
  "/home/napstar/dev/imgDrive/app/account/images/edit-dialog.tsx",
  "/home/napstar/dev/imgDrive/app/account/images/grid-view-active-image-sheet.tsx",
  "/home/napstar/dev/imgDrive/app/account/images/grid-view-image.tsx",
  "/home/napstar/dev/imgDrive/app/account/images/grid-view-selected-header.tsx",
  "/home/napstar/dev/imgDrive/app/account/images/grid-view.tsx",
  "/home/napstar/dev/imgDrive/app/account/images/img-element.tsx",
  "/home/napstar/dev/imgDrive/app/account/images/page.tsx",
  "/home/napstar/dev/imgDrive/app/account/images/share-dialog.tsx",
  "/home/napstar/dev/imgDrive/app/account/images/table-view.tsx",
  "/home/napstar/dev/imgDrive/app/signin/page.tsx",
  "/home/napstar/dev/imgDrive/components/account-header.tsx",
  "/home/napstar/dev/imgDrive/components/account-nav-main.tsx",
  "/home/napstar/dev/imgDrive/components/account-nav-user.tsx",
  "/home/napstar/dev/imgDrive/components/account-sidebar.tsx",
  "/home/napstar/dev/imgDrive/components/async-alert.tsx",
  "/home/napstar/dev/imgDrive/components/copy-button.tsx",
  "/home/napstar/dev/imgDrive/components/date-picker.tsx",
  "/home/napstar/dev/imgDrive/components/footer.tsx",
  "/home/napstar/dev/imgDrive/components/header.tsx",
  "/home/napstar/dev/imgDrive/components/image-options-form.tsx",
  "/home/napstar/dev/imgDrive/components/mode-switcher.tsx",
  "/home/napstar/dev/imgDrive/components/multi-select.tsx",
  "/home/napstar/dev/imgDrive/components/session-provider.tsx",
  "/home/napstar/dev/imgDrive/components/sign-in.tsx",
  "/home/napstar/dev/imgDrive/components/sign-out.tsx",
  "/home/napstar/dev/imgDrive/components/theme-provider.tsx",
  "/home/napstar/dev/imgDrive/components/ui/alert-dialog.tsx",
  "/home/napstar/dev/imgDrive/components/ui/aspect-ratio.tsx",
  "/home/napstar/dev/imgDrive/components/ui/avatar.tsx",
  "/home/napstar/dev/imgDrive/components/ui/badge.tsx",
  "/home/napstar/dev/imgDrive/components/ui/button.tsx",
  "/home/napstar/dev/imgDrive/components/ui/calendar.tsx",
  "/home/napstar/dev/imgDrive/components/ui/card.tsx",
  "/home/napstar/dev/imgDrive/components/ui/command.tsx",
  "/home/napstar/dev/imgDrive/components/ui/dialog.tsx",
  "/home/napstar/dev/imgDrive/components/ui/dropdown-menu.tsx",
  "/home/napstar/dev/imgDrive/components/ui/form.tsx",
  "/home/napstar/dev/imgDrive/components/ui/input.tsx",
  "/home/napstar/dev/imgDrive/components/ui/label.tsx",
  "/home/napstar/dev/imgDrive/components/ui/popover.tsx",
  "/home/napstar/dev/imgDrive/components/ui/progress.tsx",
  "/home/napstar/dev/imgDrive/components/ui/separator.tsx",
  "/home/napstar/dev/imgDrive/components/ui/sheet.tsx",
  "/home/napstar/dev/imgDrive/components/ui/sidebar.tsx",
  "/home/napstar/dev/imgDrive/components/ui/skeleton.tsx",
  "/home/napstar/dev/imgDrive/components/ui/sonner.tsx",
  "/home/napstar/dev/imgDrive/components/ui/switch.tsx",
  "/home/napstar/dev/imgDrive/components/ui/table.tsx",
  "/home/napstar/dev/imgDrive/components/ui/tabs.tsx",
  "/home/napstar/dev/imgDrive/components/ui/textarea.tsx",
  "/home/napstar/dev/imgDrive/components/ui/tooltip.tsx",
  "/home/napstar/dev/imgDrive/components/ui/kibo-ui/image-zoom/index.tsx",
  "/home/napstar/dev/imgDrive/hooks/use-meta-color.tsx"
 ],
 "options": {
  "target": 4,
  "lib": [
   "lib.dom.d.ts",
   "lib.dom.iterable.d.ts",
   "lib.esnext.d.ts"
  ],
  "allowJs": true,
  "skipLibCheck": true,
  "strict": true,
  "noEmit": true,
  "esModuleInterop": true,
  "module": 99,
  "moduleResolution": 100,
  "resolveJsonModule": true,
  "isolatedModules": true,
  "jsx": 1,
  "incremental": true,
  "plugins": [
   {
    "name": "next"
   }
  ],
  "paths": {
   "@/*": [
    "./*"
   ]
  },
  "pathsBasePath": "/home/napstar/dev/imgDrive",
  "configFilePath": "/home/napstar/dev/imgDrive/tsconfig.json"
 }
}
Info 12   [12:08:54.096] Enabling plugin next from candidate paths: /home/napstar/dev/imgDrive/node_modules/.pnpm/[email protected]/node_modules/typescript/lib/typescript.js/../../..
Info 13   [12:08:54.096] Loading next from /home/napstar/dev/imgDrive/node_modules/.pnpm/[email protected]/node_modules/typescript/lib/typescript.js/../../.. (resolved to /home/napstar/dev/imgDrive/node_modules/.pnpm/[email protected]/node_modules/node_modules)
Info 14   [12:08:54.186] [next] Initializing Next.js TypeScript plugin: /home/napstar/dev/imgDrive
Info 15   [12:08:54.208] [next] Successfully initialized Next.js TypeScript plugin!
Info 16   [12:08:54.208] Plugin validation succeeded
Info 17   [12:08:54.219] Starting updateGraphWorker: Project: /home/napstar/dev/imgDrive/tsconfig.json
Info 18   [12:09:10.513] Finishing updateGraphWorker: Project: /home/napstar/dev/imgDrive/tsconfig.json projectStateVersion: 1 projectProgramVersion: 0 structureChanged: true structureIsReused:: Not Elapsed: 15212.420032ms
Info 19   [12:09:10.513] Project '/home/napstar/dev/imgDrive/tsconfig.json' (Configured)
Info 20   [12:09:10.513]        Files (8926)

Info 21   [12:09:10.514] -----------------------------------------------
Info 22   [12:09:10.627] AutoImportProviderProject: attempted to add more than 10 dependencies. Aborting.
Info 23   [12:09:10.659] getConfigFileNameForFile:: File: /home/napstar/dev/imgDrive/app/account/images/edit-dialog.tsx ProjectRootPath: /home/napstar/dev/imgDrive:: Result: /home/napstar/dev/imgDrive/tsconfig.json
Info 24   [12:09:10.670] Project '/home/napstar/dev/imgDrive/tsconfig.json' (Configured)
Info 24   [12:09:10.671]        Files (8926)

Info 24   [12:09:10.671] -----------------------------------------------
Info 24   [12:09:10.671] Open files:
Info 24   [12:09:10.671]        FileName: /home/napstar/dev/imgDrive/app/account/images/edit-dialog-control.tsx ProjectRootPath: /home/napstar/dev/imgDrive
Info 24   [12:09:10.671]                Projects: /home/napstar/dev/imgDrive/tsconfig.json
Info 24   [12:09:10.671]        FileName: /home/napstar/dev/imgDrive/app/account/images/edit-dialog.tsx ProjectRootPath: /home/napstar/dev/imgDrive
Info 24   [12:09:10.671]                Projects: /home/napstar/dev/imgDrive/tsconfig.json
napstar@KHAN-PC:~/dev/imgDrive$

Every file loads, Next plugin loads successfully, but then I think updateGraphWorker throw some error and it says 8926 files. I don’t have 8926 files in my project

Why does CSS display: absolute push the parent content?

I thought CSS display: absolute does not affect the parent layout, but I came across a bug.

const wrapper = document.querySelector('.wrapper');
    const content = document.getElementById('content');

    // Handle mouse enter (hover in)
    wrapper.addEventListener('mouseenter', function() {
      content.classList.add('expanded');
      // Focus on the textarea when it becomes expanded
      content.focus();
    });

    // Handle mouse leave (hover out)
    wrapper.addEventListener('mouseleave', function() {
      content.classList.remove('expanded');
    });
/* Root container, which can hold other content */
    .root {
      position: relative;
      overflow: hidden;
      width: 300px;
      height: 300px;
      background-color: lightgray;
      padding: 20px;
    }

    /* The wrapper is absolutely positioned within the root */
    .wrapper {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      border: solid;
      background-color: transparent;
    }

    /* Content (textarea) to be shown/hidden within the wrapper */
    .content {
      /* position: absolute; */
      bottom: 0;
      left: 0;
      right: 0;
      padding: 20px;
      background-color: coral;
      transition: all 0.3s ease-in-out;
      opacity: 0;
      transform: translateY(100%);
      pointer-events: none;
    }

    .expanded {
      opacity: 1;
      transform: translateY(0);
      pointer-events: auto;
    }
<!-- Root container holding other elements -->
  <div class="root">
    <h2>Chat with Alice</h2>
    <p>Hi Alice</p>
    <p>Hello Bob</p>
    <p>If you click here, then hover, it will create the bug</p>
    <!-- Wrapper container that will listen for hover events -->
    <div class="wrapper">
      <!-- The sliding textarea content -->
      <textarea id="content" class="content" rows="5" cols="30">
      Type your Message To Alice
      </textarea>
    </div>
  </div>

Why does the entire parent layout jump up when I click anywhere, then hover the hover box?

enter image description here

Why is it doing that?

Proper way in JavaScript to compare two DOM elements and remove duplicates created by appendChild in loop?

I am new in JavaScript programming and trying to improve my skills. Right now I am attempting to create dynamically updated task list in which user can input the name of their task, date of competition and save it in list, from which user can remove their task. The problem is that every time user adds new task to the list the render function creates duplicates of previous task in DOM and list grows exponentially.
Here my JS code:

const taskList = JSON.parse(localStorage.getItem('taskList')) || [];
const btnElemAdd = document.querySelector('.js-button-add');

renderTaskList();

function renderTaskList() {
    const renderElem = document.querySelector('.js-render-result');
    const fragment = document.createDocumentFragment();
    for (const [i, value] of taskList.entries()) {
        const { name, dueDate } = value;
        const divName = document.createElement('div');
        const divDate = document.createElement('div');
        const btnRm = document.createElement('button');
        divName.classList.add('name');
        divDate.classList.add('date');
        btnRm.classList.add('button', 'button-rm');
        btnRm.textContent = 'Remove';
        btnRm.addEventListener('click', () => {
            rmTask(i);
        })
        divName.textContent = `${name}`;
        divDate.textContent = `${dueDate}`;
        if (!(divName.isSameNode(divName))) {
            fragment.appendChild(divName);
            fragment.appendChild(divDate);
            fragment.appendChild(btnRm);
        }

    }
    renderElem.appendChild(fragment);
}

btnElemAdd.addEventListener('click', () => {
    const inputElemName = document.querySelector('.js-input-name');
    const inputElemDate = document.querySelector('.js-input-date');
    const name = inputElemName.value;
    const dueDate = inputElemDate.value;
    taskList.push({ name, dueDate });
    inputElemName.value = '';
    renderTaskList();
    saveTaskList();
})

function saveTaskList() {
    localStorage.setItem('taskList', JSON.stringify(taskList));
}

function rmTask(index) {
    taskList.splice(index, 1);
    renderTaskList();
}

I can do this project with utilization of forEach() loop and editing innerHTML, but I cannot figure out how to do this by using appendChild . I had attempted to check on duplicates in several different ways (including isSameNode(), isEqualNode() and assigning & reassigning property to array objects) , but the solution still eludes me. And on top of that button that supposed to remove tasks from array and list does not function.

Jquery how do I append ‘‘ into a textarea as plain-text?

I am working on designing a blog from scratch and am trying to add the ability to insert <b> </b> into a textarea by clicking a button. However whenever I try to append <b> </b> nothing shows up. I was able to get other text to show up such as ‘b’ and ‘a’ so it’s something about the HTML tags it doesn’t like.

my code:

boldButton.on("click", (Event) => {
    textArea.append('<b> </b>');
})

ReferenceError: document is not defined in VSCode when trying to connect js to html and load it into chrome browser

I am trying to do a project in a Chrome browser containing HTML, CSS, and JS. They are all within the same project folder and have no visible syntax errors. I am writing the code in VSCode. Within the broswer I can view the html and css components but the js components aren’t showing up. In the terminal, it says ReferenceError: document is not defined. I know its something with loading the js file into the web browser but I’m not exactly sure what the issue is and how to fix it.

I want my js file to load in a browser with my other html and css files.

Styles not applying

**Title:** Nativewind Styles Not Applying in React Native Expo Project Despite No Build Errors

**Body:**

I’m working on a React Native project using Expo and Nativewind (Tailwind CSS for React Native). My setup compiles without errors, but Tailwind styles are not applying to my components. I’ve tried various configurations, deleted node_modules, reinstalled packages, and tested different versions, but nothing works. Modifying `babel.config.js` causes this error:

“`

Bundling failed 3618ms (C:Documentsprojectnode_modulesexpo-routerentry.js) error: appindex.jsx: [BABEL] C:Documentsprojectappindex.jsx: .plugins is not a valid Plugin property

“`

The current configuration (below) builds without errors, but styles don’t apply. Can someone identify the issue and help fix it so Nativewind styles work correctly?

**package.json:**

“`json

{

“name”: “mobile-app”,

“version”: “1.0.0”,

“main”: “index.js”,

“scripts”: {

"start": "expo start",

"android": "expo start --android",

"ios": "expo start --ios",

"web": "expo start --web"

},

“dependencies”: {

"@expo/vector-icons": "^14.1.0",

"@react-native-async-storage/async-storage": "1.21.0",

"@react-navigation/bottom-tabs": "^6.5.20",

"@react-navigation/native": "^6.1.17",

"@react-navigation/stack": "^6.3.29",

"axios": "^1.6.8",

"babel-preset-expo": "^10.0.2",

"expo": "~50.0.14",

"expo-document-picker": "~11.10.1",

"expo-image-picker": "~14.7.1",

"expo-location": "~16.5.5",

"expo-secure-store": "~12.8.1",

"expo-status-bar": "~1.11.1",

"expo-task-manager": "~11.7.2",

"nativewind": "^4.1.23",

"react": "18.2.0",

"react-native": "0.73.6",

"react-native-gesture-handler": "~2.14.0",

"react-native-maps": "1.10.0",

"react-native-reanimated": "~3.6.2",

"react-native-safe-area-context": "4.8.2",

"react-native-screens": "~3.29.0",

"socket.io-client": "^4.7.5",

"expo-splash-screen": "~0.26.5",

"expo-font": "~11.10.3"

},

“devDependencies”: {

"@babel/core": "^7.20.0",

"tailwindcss": "^3.4.17"

},

“private”: true

}

“`

**tailwind.config.js:**

“`js

/** @type {import(‘tailwindcss’).Config} */

module.exports = {

content: [

"./app/**/*.{js,jsx,ts,tsx}",

"./components/**/*.{js,jsx,ts,tsx}"

],

theme: {

extend: {},

},

plugins: [],

}

“`

**babel.config.js:**

“`js

module.exports = function(api) {

api.cache(true);

return {

presets: [

  ['babel-preset-expo', { jsxImportSource: 'nativewind' }],

  'nativewind/babel',

],

plugins: [],

};

}

“`

**What I’ve Tried:**

1. Deleted `node_modules` and `package-lock.json`, reinstalled with `npm install`.

2. Tested different versions of `nativewind`, `tailwindcss`, and `babel-preset-expo`.

3. Modified `babel.config.js` to add/remove plugins, but got the `[BABEL] .plugins is not a valid Plugin property` error.

4. Ensured components use Tailwind classes (e.g., `<View className=”bg-blue-500″>`).

5. Verified `tailwind.config.js` content paths.

6. Cleared Expo cache with `expo start –clear`.

**Additional Context:**

– Using Expo SDK 50.0.14, Nativewind 4.1.23, Tailwind CSS 3.4.17.

– Project builds/runs without errors, but Tailwind styles (e.g., `bg-blue-500`) don’t apply.

– Testing on Android emulator, issue persists across platforms.

**Question:**

Why aren’t Tailwind styles applying despite a successful build? Is there an issue with `babel.config.js`, `tailwind.config.js`, or another setup? How can I fix this to get Nativewind working without errors?

**Tags:** react-native, expo, nativewind, tailwind-css, babel

Why am I getting an exception after creating a JSON object and attempting to pass it to a save method?

Code snippet:

const saveData = function (callback) {
  app.ajax.postJsonAsync(
    'err/details/save',
    getErrRef(),
    true,
    function (data, textStatus, jqXhr) {
      app.ajax.handleResponse(data, textStatus, jqXhr, { onSuccess: callback });
    },
  );

  const getErrRef = function () {
    return {
      //Jurisdiction : $("#jurisdiction option:selected").text()
    };
  };
};

When this code executes (notice I have commented out Jurisdiction), the function returns an empty object, so when it gets passed to the save, it at least reaches that method. However, if I uncomment Jurisdiction, I get the following error somewhere in between the javascript function and the save method. The save method is never reached. This is the error:

System.ArgumentException: An item with the same key has already been added.

I do not know what I am doing wrong.

How can I clear or reduce the amount of memory a Javascript injection is taking up in the browser?

I’m currently attempting to access metadata off of an online video stream by running the video player in Selenium in python and attempting to return any data from the metadata parser. This is my current code:

driver.execute_script("""
                window.__metaDataCaptured__ = [];
                function hookParserOutput(data) {
                    window.__metaDataCaptured__.push(data)
                }

                const oldParser = metaDataParser.parse
                metaDataParser.parse = function(msg) { 
                    result = oldParser(msg)
                    hookParserOutput(result)
                } 
""")
time.sleep(5)

while True:
    result = driver.execute_script("""
            const data = window.__metaDataCaptured__ || [];
            window.__metaDataCaptured__ = null;  // clear after read
            window.__metaDataCaptured__ = [];  // clear after read
            return data;
                                """)
    if result != []:
        print(result)

Right now, the website slows down significantly after a couple of minutes and crashes after around 20 minutes.

Eventually I’d like to push the result data to another structure, but I’m printing for now. I’ve tried my best to remove any memory leaks by reusing variable names and clearing __metaDataCaptured__, but after just a couple of minutes the Developer Tools show memory usage at hundreds of megabytes, which is primarily taken up by strings, mostly the data I’m trying to intercept.

I figured that constantly executing a new script is not great for performance. Is there a way I can either

  1. Constantly stream new data to my python code without running a new script each time, or
  2. Clear the data after it’s been received so it doesn’t take up so much memory?

Firestore Security Rules: Getting all docs with field specific where query

As mentioned in the positive example of the Firestore Documentation I tried the query with the where condition, but it didn’t work (premission error):

getDocs(query(collection(db, 'users'), where('shareWith', 'array-contains', email)))
  .then(q => q.forEach(doc => console.log(doc.id, " => ", doc.data())))
;

Why does it not work with the following rule?

match /users/{userId}/{documents=**} {  
  allow read: if request.auth.token.email in get(/databases/$(database)/documents/users/$(userId)).data.shareWith;
  allow read, write: if request.auth.uid == userId;
}

PS: What works with the rule above, is accessing a specific user document though (for example users/123).

How to get element from injected html (page)

How to get specific element from injected html?

I want to get element ELEM[ATTE="VAL"] under div = document.querrySelector('DIV#elemWithHtml') but (div/document).querrySelectorAll('ELEM[ATTR="VAL"]') returns null.

Also it does not recognize HTML as child element.

I am using Firefox if it makes any difference.

Example:

<div id="elemWithHtml">
 ---
 <!-- injectet html -->
 <html>
     <head></head>
     <body>
         ----
         <elem attr="val"> <!-- wanted element -->
         ----
     </body>
 </html>
 ---
 </div>

var div = document.querrySelector('DIV#elemWithHtml');
var findElem = function (el) {
    for (let c of el.children) {
    if(/elem/gi.test(c.nodeName)) {
        if(/val/gi.test(c.getAttribute('attr')))
            return c;
    }
    let r = findCB(c);
    if (!!r)
        return r;
    }
    return null;
}

var f = findElem(div);

or

var f = div.querrySelector('ELEM[ATTR="VAL"]');

I want “f” to contain wanted element;

Sorry I do not know how to properly format it

when I run “npm run watch:js”,it change app.js file code

I have a Node.js project, and after the Parcel update, I’m running into an issue.

In my ./public/js/ folder I have 2 files: bundle.js and bundle.js.map. Previously, Parcel was compiling/bundling the code in these 2 files. However, after the update, it’s now changing my app.js file. And I can’t figure out how to adjust the parcel to the before-mentioned 2 files.

This is my package.json file

{
  "name": "Project",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "start": "nodemon server.js",
    "watch:js": "parcel watch ./public/js/index.js --dist-dir ./public/js/bundle.js",
    "build:js": "parcel watch ./public/js/index.js --dist-dir ./public/js/bundle.js"
    }
 "dependencies": {
    "@babel/polyfill": "^7.12.1",
    "axios": "^1.10.0"
  },
  "devDependencies": {
    "parcel": "^2.15.4".
}

Using Pascal-bundle, I want to run this code from the index.js file

Login.js file

import axios from 'axios'
export const login=async(email,password)=>{ 
    try{
        const res=await axios({
            method:'POST',
            url:'http://127.0.0.1:7000/api/v1/user/login',
            data:{
                email,
                password
            }
        })
        if(res.data.status==='success'){
            alert('Logged in Successfully!')
            window.setTimeout(()=>{
                location.assign('/')
            },1500)
        }
        
    }catch(err){
        alert(err.response.data.message)
    }
}
console.log('the document is: ',document.querySelector('.form'))

index.js file

import '@babel/polyfill'
import {login} from './login'
document.querySelector('.form').addEventListener('submit',e=>{
    e.preventDefault()
    const email=document.getElementById('email').value;
    const password=document.getElementById('password').value;
    login(email,password)
})

When I run the ‘npx parcel build ./public/js/js/index.js –dist-dir ./public/js –no-cache’ command or the ‘npm run watch’ command. This command changes my app.js file.

Before executing the command, my app.js file

app.use('/',viewRoute)
app.use('/api/v1/tours',tourRoute)
app.use('/api/v1/user',userRoute)
app.use('/api/v1/review',reviewRoute)
app.all('*',(req,res,next)=>{
  next(new AppError(`Can't find ${req.originalUrl} on this server!`,404))})

After running the command on my app.js file, it automatically generates this code

require("@babel/polyfill");
var $knI9B$axios = require("axios");
const $70af9284e599e604$export$596d806903d1f59e = async (email, password)=>{
    try {
        const res = await (0, ($parcel$interopDefault($knI9B$axios)))({
            method: 'POST',
            url: 'http://127.0.0.1:7000/api/v1/user/login',
            data: {
                email: email,
                password: password
            }
        });
        if (res.data.status === 'success') {
            alert('Logged in Successfully!');
            window.setTimeout(()=>{
                location.assign('/');
            }, 1500);
        }
    } catch (err) {
        alert(err.response.data.message);
    }
};
console.log('the document is: ', document.querySelector('.form'));
document.querySelector('.form').addEventListener('submit', (e)=>{
    e.preventDefault();
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;
    (0, $70af9284e599e604$export$596d806903d1f59e)(email, password);
});


//# sourceMappingURL=app.js.map

I want to try to executed this code into bundle.js and bundle.js.map . Not executed in app.js and does not make app.js.map file

require("@babel/polyfill");
var $knI9B$axios = require("axios");
const $70af9284e599e604$export$596d806903d1f59e = async (email, password)=>{
    try {
        const res = await (0, ($parcel$interopDefault($knI9B$axios)))({
            method: 'POST',
            url: 'http://127.0.0.1:7000/api/v1/user/login',
            data: {
                email: email,
                password: password
            }
        });
        if (res.data.status === 'success') {
            alert('Logged in Successfully!');
            window.setTimeout(()=>{
                location.assign('/');
            }, 1500);
        }
    } catch (err) {
        alert(err.response.data.message);
    }
};
console.log('the document is: ', document.querySelector('.form'));
document.querySelector('.form').addEventListener('submit', (e)=>{
    e.preventDefault();
    const email = document.getElementById('email').value;
    const password = document.getElementById('password').value;
    (0, $70af9284e599e604$export$596d806903d1f59e)(email, password);
});

I’ve tried a number of things to fix it, and continually get this same output.

Thank you advance