WebAuthn passkey prompt not appearing in Firefox 137 on Windows 11

I’m working on a login flow that uses WebAuthn passkey authentication on the frontend. The implementation works fine in Chrome and Edge, but the passkey prompt does not appear at all in Firefox version 137, running on Windows 11 24H2.

Here’s the relevant part of the JavaScript code:

navigator.credentials.get({
  publicKey: {
    challenge: Uint8Array.from(window.atob(challenge), c => c.charCodeAt(0)),
    allowCredentials: [{
      id: Uint8Array.from(window.atob(credentialId), c => c.charCodeAt(0)),
      type: "public-key"
    }],
    timeout: 60000,
    userVerification: "preferred"
  }
}).then(assertion => {
  // Handle successful assertion
}).catch(err => {
  console.error('WebAuthn failed:', err);
});

Is there an extra configuration needed in Firefox for passkey-based WebAuthn to work on Windows? Or is this a known issue in Firefox 137?

Thanks in advance for any help!

Detect single word text selection using javascript on android

I want to detect when a user finishes making a text selection on android, using cordova and javascript. This is possible for multi-word selections (see the gist by parthibeyond, added at the end of the question for completeness), but it does not work for a single word selection. When initiating a selection by touching and holding a word the following events are fired in sequence:

  1. selectstart
  2. contextmenu
  3. selectionchange
  4. touchcancel

At this point, the user can either lift their finger to select only the initial word, or move it while still touching the screen to select additional words. Is there any way to detect the first case of single word selection? The touchcancel event prevents the touchend event from being fired, and a timer is not useful since the user may hold the finger still for an arbitrary amount of time before moving it for multi-word selection.

The OS indicates the removal of the finger, indicating the end of the selection, for both single and multi-word selection by adding “grab handles” at either end of the selected text:

Finger touching screen (context menu suppressed for clarity)

Finger touching screen

Finger removed from screen

Finger removed from screen

Is there any way to get this event in javascript?

The only workaround I can find is to call event.preventDefault() on touchstart but this removes all text selection and scrolling functionality.

Code for multi-word selection end event, credit parthibeyond

function customisedSelectListener(el = document, callbackFn) {
  // events to be listened - 'selectstart', 'selectionchange', 'contextmenu'
  let eventSequence = [];

  el.addEventListener('selectstart', function() {
    eventSequence = [];
    eventSequence.unshift(event.type);
  })

  el.addEventListener('selectionchange', function() {
    if (eventSequence[0] != 'selectionchange') {
      eventSequence.unshift(event.type);
    }
  })

  el.addEventListener('contextmenu', function() {
    eventSequence.unshift(event.type);
    if (eventSequence[1] == 'selectionchange') {
      callbackFn.call();
    }
  })
}

Usage:

customisedSelectListener(document, function (){
  alert('Text Selection Completed !!');
})

Why do my floating leaves appear at the same time and barely move?

I’m trying to create a floating leaf animation using CSS and a parallax effect with JavaScript. My goal is to have multiple leaves float in slightly different paths and timings across the screen.

But right now:

  • All the leaves appear at the same time, even though I added animation-delay.
  • The float animation moves them in a very small range.
  • I also added a mouse-based parallax effect and wonder if that’s interfering with the animation?

Here’s a simplified version of my code:

HTML:

<div class="floating-leaf" id="leaf1"><img src="images/leaf.png" /></div>
<div class="floating-leaf" id="leaf2"><img src="images/leaf.png" /></div>
<div class="floating-leaf" id="leaf3"><img src="images/leaf.png" /></div>

CSS

.floating-leaf {
  position: absolute;
  width: 24px;
  height: 24px;
  z-index: 1;
  animation: float 12s linear infinite;
  opacity: 0.7;
}

@keyframes float {
  0% {
    transform: translate(0, 0) rotate(0deg);
    opacity: 0;
  }
  10%, 90% { opacity: 0.7; }
  100% {
    transform: translate(100px, -100px) rotate(360deg);
    opacity: 0;
  }
}

#leaf1 { top: 80px; left: 10%; animation-delay: 0s; }
#leaf2 { top: 50px; left: 80%; animation-delay: 1s; }
#leaf3 { top: 30px; left: 45%; animation-delay: 2s; }

JavaScript (for parallax):

function initLeafParallax() {
  window.addEventListener('mousemove', function(e) {
    const leaves = document.querySelectorAll('.floating-leaf');
    leaves.forEach((leaf, index) => {
      const speed = (index + 1) * 0.03;
      const x = (window.innerWidth - e.pageX * speed) / 100;
      const y = (window.innerHeight - e.pageY * speed) / 100;
      leaf.style.transform = `translate(${x}px, ${y}px)`; // could this be overriding CSS animation?
    });
  });
}

How can I make the leaves float more realistically and not all show up at the same time?
Any help is appreciated!

Bootstrap modal working proper but not with overlay component

The current interaction behavior is that after I click submit the form, it should have delayed time with spinner and success message but they’re still not showing only modal close in setTimeout() inside showSuccess()

I have modal overlay after modal-footer and inside modal-content

<div id="modalOverlay" class="position-absolute top-0 start-0 w-100 h-100 d-flex flex-column justify-content-center align-items-center" style="z-index: 1000;">
    <div id="loadingSpinner" class="spinner-border text-primary d-none" role="status">
        <span class="visually-hidden">Loading...</span>
    </div>

    <div id="successMessage" class="alert alert-success mt-3 d-none" role="alert">
        Added Successully!
    </div>
</div>

function hideAddModal() {
    document.getElementById("modalOverlay").style.pointerEvents = "none";
    $("#addModal").modal("hide");
    $(".modal-backdrop").remove();
}
function showSpinner() {
    $("#loadingSpinner").removeClass("d-none");
    $("#successMessage").addClass("d-none");
    document.getElementById("modalOverlay").style.pointerEvents = "auto";
}
function showSuccess() {
    $("#loadingSpinner").addClass("d-none");
    $("#successMessage").removeClass("d-none");
    document.getElementById("modalOverlay").style.pointerEvents = "auto";

    setTimeout(function () {
        hideAddModal();
        $("#successMessage").addClass("d-none");
    }, 1000)
}

Below here is code snippet of submit function after button is triggered

bool isInserted = await InsertStored(value);
if (isInserted)
{
    BindGridView(); 
    Debug.WriteLine("Registering script to hide modal");
    ScriptManager.RegisterStartupScript(this, GetType(), Guid.NewGuid().ToString(),
    @"
    showSpinner();
    setTimeout(function() {
        showSuccess();
    }, 500);
    ",
    true);
}
else
{
    // Another ScriptManager to show alert error message
}

How do optimise Array.sort or what is the best way to sort large size JSON

i am using default array.sort method inside my application here is my sample code

  const jsonArray = Array.from({ length: 100000 }, (_, i) => ({
  id: i,
  principle: Math.random() * 1000,
  interest: Math.random() * 1000,
  maturity: Math.random() * 1000,
  maturity_date: new Date(Date.now() + Math.random() * 100000000).toISOString(),
  maturity_amount: Math.random() * 1000,
  maturity_amount_date: new Date(Date.now() + Math.random() * 100000000).toISOString(),
  maturity_amount_value: Math.random() * 1000,
  maturity_amount_date_value: Math.random() * 1000,
  maturity_amount_date_value_date: new Date(Date.now() + Math.random() * 100000000).toISOString(),
  maturity_amount_date_value_name: `Name ${Math.random() * 100000}`,
  maturity_amount_date_value_name_date: new Date(Date.now() + Math.random() * 100000000).toISOString(),
  maturity_amount_date_value_name_date_value: Math.random() * 1000,
  name: `Name ${Math.random() * 100000}`,
  value: Math.random() * 1000,
}));
//console.log(jsonArray);

console.time('Sort time');
const sortedArray = jsonArray.sort((a, b) => a.name.localeCompare(b.name)); // Sort by 'name' in ascending order
console.timeEnd('Sort time');

Which is taking 371 ms Sort time: 371.35400390625 ms what is the best way to sort this in such a way that time to bring sort time around 180ms or so.

Prisma won’t connect to the API I Created

Now that is the error when I try to save the course name the error handling message always pop up
so I checked connection of Prisma with MySQL database and it was fine.
I did npx prisma generate and npx prisma push db and it run fine.
So I was trying so understand the problem since every thing is well connected and the api is written right what is the problem here is the code and the error

this is the on Submit

const onSubmit = async (values: z.infer<typeof formSchema>) => {
    try{
        const reponse = await axios.post("/api/courses", values)
        router.push(`/teacher/courses/${reponse.data.id}`);
        toast.success("Course created successfully")
            }catch{
                toast.error("Something went wrong")
            }
    };

While this is the route.ts at the apicourses folder

import { db } from "@/lib/db";
import { auth } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";

export async function POST(
    req: Request,
) {
    try {
        const { userId } = await auth();
        const { title } = await req.json();

        if (!userId) {
            return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
        }

        const course = await db.course.create({
            data: {
                title,
                userId,
            },
        });

        return NextResponse.json(course);

    } catch (error) {
        console.log("[COURSES]", error);
        return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
    }
}
npm run dev

> [email protected] dev
> next dev

   ▲ Next.js 15.3.1
   - Local:        http://localhost:3000
   - Network:      http://192.168.1.15:3000
   - Environments: .env

 ✓ Starting...
 ✓ Ready in 6.7s
 ○ Compiling /middleware ...
 ✓ Compiled /middleware in 4.5s (224 modules)
<w> [webpack.cache.PackFileCacheStrategy] Serializing big strings (117kiB) impacts deserialization performance (consider using Buffer instead and decode when needed)
 ○ Compiling /teacher/create ...
 ✓ Compiled /teacher/create in 19.9s (1659 modules)
 GET /teacher/create 200 in 22577ms
 ○ Compiling /favicon.ico ...
 ✓ Compiled /favicon.ico in 2.2s (1017 modules)
 GET /favicon.ico 200 in 2729ms
 ○ Compiling /api/courses ...
 ✓ Compiled /api/courses in 2.1s (1667 modules)
Initializing Prisma Client...
 ⨯ Error: @prisma/client did not initialize yet. Please run "prisma generate" and try to import it again.
    at eval (libdb.ts:8:35)
    at <unknown> (rsc)/./lib/db.ts (D:WorkMy ProjectsLMSrpm-lms0.2.nextserverappapicoursesroute.js:33:1)
    at __webpack_require__ (D:WorkMy ProjectsLMSrpm-lms0.2.nextserverwebpack-runtime.js:33:42)
    at eval (webpack-internal:///(rsc)/./app/api/courses/route.ts:5:65)
    at <unknown> (rsc)/./app/api/courses/route.ts (D:WorkMy ProjectsLMSrpm-lms0.2.nextserverappapicoursesroute.js:22:1)
    at __webpack_require__ (D:WorkMy ProjectsLMSrpm-lms0.2.nextserverwebpack-runtime.js:33:42)
    at __webpack_require__ (D:WorkMy ProjectsLMSrpm-lms0.2.nextserverwebpack-runtime.js:33:42)
    at __webpack_exec__ (D:WorkMy ProjectsLMSrpm-lms0.2.nextserverappapicoursesroute.js:184:39)
    at <unknown> (D:WorkMy ProjectsLMSrpm-lms0.2.nextserverappapicoursesroute.js:185:309)
    at __webpack_require__.X (D:WorkMy ProjectsLMSrpm-lms0.2.nextserverwebpack-runtime.js:168:21)
    at <unknown> (D:WorkMy ProjectsLMSrpm-lms0.2.nextserverappapicoursesroute.js:185:47)
    at Object.<anonymous> (D:WorkMy ProjectsLMSrpm-lms0.2.nextserverappapicoursesroute.js:188:3)
   6 |
   7 | console.log("Initializing Prisma Client...");
>  8 | export const db = global.prisma || new PrismaClient();
     |                                   ^
   9 |
  10 | if (process.env.NODE_ENV !== "production") {
  11 |     global.prisma = db; {
  page: '/api/courses'
}

How to debug extension service worker silently failing

When working on a extension service worker (MV3), many times a bug will cause the service worker to silently fail, making it remain inactive, and as far as I can tell without a way to attach Chrome DevTools to it, making it very difficult to determine what is the bug to begin with.
For example if I include something like:

import { dne } from './not-a-file';

anywhere in the service worker or imported submodules, it will not activate. And any communication will silently fail as well, for example calling from the popup window (and obviously calling sendResponse on the other end):

console.log("before message");
const response = await chrome.runtime.sendMessage("hello");
console.log("after message");
console.log(response);

will only log

before message

in the DevTools attached to the popup window. Is there a way to deal with these silent failures?

Calculating offset to center a card in a carousel

I’m working on this React x Motion carousel that brings a card to the center of the screen when it has been clicked, depending on its index. However, the cards only seem to be placed at the start of the carousel list.
Here is the code below.

import { motion } from "motion/react";
import { useState } from "react";

const carouselImages = [
  "../img-11.jpg",
  "../img-2.jpg",
  "../img-13.jpg",
  "../img-4.jpg",
  "../img-15.jpg",
  "../img-1.jpg",
  "../img-19.jpg",
  "../img-3.jpg",
  "../img-14.jpg",
  "../img-5.jpg",
];

export default function StaggerCarousel() {
  const [selectedIndex, setSelectedIndex] = useState(0);

  const handleOnClick = (e) => {
    const clickedItem = e.currentTarget;
    const clickedIndex = Array.from(clickedItem.parentNode.children).indexOf(
      clickedItem
    );
    setSelectedIndex(clickedIndex);
  };

  return (
    <div className="carousel-container w-screen h-screen flex items-center justify-center bg-gray-900">
      <motion.ul className="carousel-list flex items-center h-full overflow-hidden w-[90vw] md:w-150 gap-4">
        {carouselImages.map((img, index) => {
          return (
            <motion.li
              key={index}
              className="carousel-item w-48 h-48 rounded-lg shrink-0 cursor-pointer"
              animate={{
                translateX: `-${selectedIndex * 100}% `,
                y: selectedIndex === index ? -20 : 10,
                rotate: selectedIndex === index ? 0 : 5,
                opacity: selectedIndex === index ? 1 : 0.5,
                transition: {
                  duration: 0.05,
                  //   delay: index * 0.1,
                  type: "spring",
                  stiffness: 100,
                },
              }}
              style={{
                backgroundImage: `url(${img})`,
                backgroundSize: "cover",
                backgroundPosition: "center",
              }}
              onClick={handleOnClick}
            ></motion.li>
          );
        })}
      </motion.ul>
    </div>
  );
}

I can visualize that the calculation will be dependent on the windowWidth and itemWidth, and I’ve tried something like that, but it doesn’t give the exact result.


  const itemWidth = 208;

  const windowWidth = window.innerWidth / 2;

  const offsetX = windowWidth + itemWidth / 2 - selectedIndex * itemWidth;
  console.log(offsetX);

Unknown JSON.stringify issue [duplicate]

I’ve been writing a chatbot for a site, and am working on a command that gives a (non–existant, fake) currency on the bot to buy fun items, and I’m using localStorage and JSON objects for that.

But, I’ve encountered an issue when updating the balance of the user and creating a new balance value for the user, here are the details:

if (localStorage.balances == undefined) {
    localStorage.setItem('balances', '{"ffdbddfaae": "0"}') // initialize balance so JSON doesn't error out
}
let balances = JSON.parse(localStorage.balances) // convert string to JSON object for further changes

let addToBalance = function(value, id) {
    if (id.replace(/[0-9]/g, '') in balances) { // convert alphaumerical id string to only letters to not cause errors when using balances.(id) and check if id exists in balance object
        Object.defineProperty(balances, id.replace(/[0-9]/g, ''), {
            value: parseInt(balances[id]) + value // add value to balance 
        })
        localStorage.setItem("balances", JSON.stringify(balances))
    } else {
        Object.defineProperty(balances, id.replace(/[0-9]/g, ''), {
            value: value
        })
        localStorage.setItem("balances", JSON.stringify(balances))
    }
}
addToBalance(100, "ffdbddfaae")
addToBalance(69, "foobarid")

The code should work in theory, but it doesn’t.
Here is how I analyzed the code.

  1. Try isolated code in isolated environment
  2. Check localStorage.balances
  3. Note that it didn’t change at all
  4. Dissect the problem

So when dissecting the problem, I found out that when JSON.stringify()ing the new balances variable (not to be confused with localStorage.balances), instead of being '{"ffdbddfaae": 100, "foobarid": 69}', it was just '{"ffdbddfaae": 0}', aka the first value that localStorage.balance was set to, so, in practice, localStorage.balance was changing to its own value, creating no effect whatsoever.

Any reason why that happens?
Maybe I’m just too new to JSON.

page history combined with the history of an iframe on the page

I’m working in an application written in Perl, JavaScript, CSS, and C. I have a visual with an iframe that loads an application about the visual and a history.go(-1) breadcrumb. If I click into the application in the iframe and then click the breadcrumb, it backs through the iframe history before leaving the visual. The visual and iframe history seem combined. I would like to allow a client to explore the application in the iframe and leave the visual page without backing through the iframe history. I have tried some eventlisteners and have been looking at the iframe-history,js function set on Gethub. So far, I’ve not been able to do it. Any guidance would be appreciated. Thanks.

tsconfig/linter to prevent named import of CJS module from ESM

To import a CJS module from an ESM module, the “default import” has to be used, while named imports cause an error when ran.

// Errors as lodash is CJS module.
import { get } from 'lodash';

// OK.
import _ from 'lodash';
const get = _.get;

Is there a way to detect, in the code IDE, incorrect named imports of CJS module, via tsconfig, eslint, or otherwise?

Javascript dynamic javascript file loading then execution

here is the execution of my javascript:

ee_btn.addEventListener('click', () => {
        //Ajax GET request to get data form and rendering it
        RequestEEFormData(container, bounds).then(()=>{
            // Loading a javascript file. it get loaded.
            // I can call function from this file then.
            loadScript('/static/js/locationConverterWidget.js');
        });
        
    });
function loadScript(url) {
    const script = document.createElement('script');
    script.src = url;
    script.async=false;
    script.onload = function(){
        //trying to querySelector newly added content
        console.log(document.querySelector('#id_item);
    }
    document.head.appendChild(script);
  }

in case:


async function RequestEEFormData(container, bounds) {
    $.ajax({
        type: 'GET',
        url: 'someURL/',

        success: function (response) {
           container.innerHTML=response;
           someFunction(bounds)
        },
        error: function(response){
          console.log(response);
        },
        cache:false,
        contentType: "application/json",
        processData: false
     });
}

the console.log return an empty Nodelist.

if I do call the same consol.log from a button 1sec later. It work.

Clearly there is something with the async I dont understand.

Can anyone explain my what I’m doing wrong ?

the purpose is I want the newly downloaded javascript file to querySelector newly added content but It seems to be executed prior the html is completely rendered.

thank you

react-map-gl Popup displaying under deck.gl layers

I’m using a react-map-gl Popup component (maplibre implementation) inside a DeckGl component, and while I can get the Popup to open, it seems to be displaying under the deck.gl layers. To illustrate what’s happening vs the desired behavior, in the image below, the green border should be visible over the pink circle:

deckgl layer vs popup:

My component structure is as follows:

<DeckGL
  layers={layers}
  initialViewState={INITIAL_VIEW_STATE}
  controller={true}
>
  <Map reuseMaps mapStyle={MAP_STYLE}>
    {selectedLocation && (
      <Popup
        longitude={selectedLocation.geometry.coordinates[0]}
        latitude={selectedLocation.geometry.coordinates[1]}
        closeButton={true}
        onClose={() => setSelectedLocation(undefined)}
        offset={[0, -15]}
      >
        <h3>HELLO WORLD</h3>
      </Popup>
    )}
  </Map>
</DeckGL>  

And my layer config is:

const layers = [
  new GeoJsonLayer({
    id: "PinkDotsLayer",
    data: pinkDotsGeoData,
    getPointRadius: 25,
    getFillColor: [255, 0, 255],
    pickable: true,
    onClick: handleLocationClick,
  }),
  new GeoJsonLayer({
    id: "PurpleDotsLayer",
    data: purpleDotsGeoData,
    getPointRadius: 25,
    getFillColor: [128,0,128],
    pickable: true,
    onClick: handleLocationClick,
  }),
];

I’m aware of the integration modes documentation, but I’m not quite sure how to modify my code accordingly as the provided code sample does not work for me.

How should I go about getting the Popup to display at the top-most layer?

How do I use console.log in JavaScript? [closed]

I’m just starting to learn JavaScript and I keep seeing people use console.log().

Can someone explain:

What the JavaScript console is?

How do I use it to test or debug my code?
your text
Here’s what I’ve tried:

javascript
Copy
Edit
console.log(“Testing the console”);