save to file from firefox extension

I want to pass a single number from Firefox extension to external world, so that another application can get it. The only solution I can think of is to write it to a file in some known location, but I cannot find any simple way to do it. I’ve already tried Indexeddb and Nativemessages APIs according to Mdn, and failed.

So, what way is simplest or where can I find some good easy tutorial how to do it?

Nextjs loading Third Party Scripts which add to window load event

I see this as common practice with a lot of third party scripts where they have an initialization function that gets attached to window load event so that on page load, the script does what it needs to do. This doesn’t seem to work well in an SPA. Let me explain.

Lets say you have a client component that uses the Script component, then the page is loaded and the component is mounted, the script is added, it adds its function to window load event, load event eventually fires, then the components target element gets modified as intended.

But here’s the issue, if you were to navigate away, that’s not considered a new page load, that’s just a route change. So if I were to leave that page and go back using Link’s for example, once I return to that page with the component loading the script, the script doesn’t actually do anything anymore. The load event has already fired at the beginning of the application lifecycle so the script wouldn’t initialize when the component is mounted again.

This is not an edge case with the script. It is common practice for scripts to leverage window load for initialization. Load event doesn’t fire more than once in the lifecycle of the session in an SPA.

What’s the intended way to do this in Next.js?

Here is an example component.

'use client';
import Script from 'next/script';

function ExampleComponent() {
  return (
    <>
      <Script src="example_script.js" />
      <div id="exampleContainer"></div>
    </>
  )
}

Here is an example of what could be the contents of the example script

// a bunch of minified code that doesn't matter for the question
...
window.addEventListener("load", scriptsInitFunction);

Redux toolkit query throwing error on using in components

I am getting an error in the code while using redux tool kit in my application

(0, middlewares_socket_middleware_WEBPACK_IMPORTED_MODULE__2_useSendMessgeQuery) is not a function.

Here is my code which I am using

//middleware

const socket = new WebSocket("//url");
const connectToWebSocket = new Promise((resolve, reject) => {
try {
  socket.addEventListerner("open", (evt) => {
   resolve(evt)
  })
} catch (e) {
   reject(e)
}
})

const webSocketApi = createApi({
   reducerPath: "webSocket",
   async baseQuery({type, topic}) {
    await connectToWebSocket;
    const socketPlayload = {id: nanoid(), type, path: topic};
    socket.send(JSON.stringify(socketpayload));
   },
   endPoints: (builder) => ({
    sendMessage: builder.mutation({
      query({type, topic}) {
       return {type, topic};
      }
    }),
    channel: builder.query({
      queryFn() {
         return null;
      },
      async onCacheEntryAdded(topic, {cacheDataLoaded, updateCacheData, cacheEntryRemoved}) {
       await cacheDataLoaded;
       socket.addEventListerner('message', (evt) => {
          updateCacheData((draft) => {
           draft.data = JSON.strinigify(evt.data);
           await cacheEntryRemoved;
           socket.close()
          })
       })
    }
   })
 })

})
In my component I am trying to call the query by using

const {data, isSuccess} = useSendMessageQuery();

Identifying what element loads a Web code [closed]

There is a Web page that loads some Javascript code and does some actions. I am using Chrome Dev Tools to identify from where this code is loaded.

The reference to the code can be found in the event listeners section (since the code creates an event listener). It appears like this:

enter image description here

This code points to a script like:

debugger:///VM*

So I assume it is something dynamically created, not a script that is loaded as a Web resource like myscript.js.

This makes it difficult to understand how the code is created, what script created it and how it ended up running in my browser.

Is there any tool in the Dev Tools or somewhere else that I can use to identify the source of this code?

How to create custom tailwind react components [closed]

I want to create a a library of custom components with specific tailwind stylings that are functionally the same as a standard react HTMLButton,. For example I want to create a element that has all of the same properties and functionality as a standard element (onClick, active, etc), but when it is rendered it is rendered with my custom styling without having to set the className property over and over on standard elements.

How do I go about this? I am struggling to wrap my head around React’s implementation of extending React.Component and the documentation states that method is deprecated now anyway

Redux toolkit query cannot use in components

I am getting an error in the code while using redux tool kit in my application

(0, middlewares_socket_middleware_WEBPACK_IMPORTED_MODULE__2_useSendMessgeQuery) is not a function.
Here is my code which I am using
//middleware

const socket = new WebSocket("//url");
const connectToWebSocket = new Promise((resolve, reject) => {
try {
  socket.addEventListerner("open", (evt) => {
   resolve(evt)
  })
} catch (e) {
   reject(e)
}
})

const webSocketApi = createApi({
   reducerPath: "webSocket",
   async baseQuery({type, topic}) {
    await connectToWebSocket;
    const socketPlayload = {id: nanoid(), type, path: topic};
    socket.send(JSON.stringify(socketpayload));
   },
   endPoints: (builder) => ({
    sendMessage: builder.mutation({
      query({type, topic}) {
       return {type, topic};
      }
    }),
    channel: builder.query({
      queryFn() {
         return null;
      },
      async onCacheEntryAdded(topic, {cacheDataLoaded, updateCacheData, cacheEntryRemoved}) {
       await cacheDataLoaded;
       socket.addEventListerner('message', (evt) => {
          updateCacheData((draft) => {
           draft.data = JSON.strinigify(evt.data);
           await cacheEntryRemoved;
           socket.close()
          })
       })
    }
   })
 })

})
In my component I am trying to call the query by using

const {data, isSuccess} = useSendMessageQuery();

Identifying what element loads a Web code

There is a Web page that loads some code. I am using Chrome Dev Tools to identify where it is loaded and what actually loads the script.

I can find the code through the event listeners. However, they pointed me to

debugger:///VM742

So I assume it is something dynamically created.

Is there any tool in the Dev Tools or somewhere else that I can use to identify how this code ends up running in my browser?

how to build a website with coding while im a beginner [closed]

I want to build a website. the thing is i know nothing about programming. How should I start? and what is that I should be focusing on in regard to languages? the website will be for articles and knowledge acquisition in general. nothing too fancy.

my brother is telling me to skip all the languages crap and just create the site with WordPress. is it recommended?

Pieces on a game field don’t follow rules [closed]

Making a little game in Javascript and I seem to not have “explained” the rules to the code properly. The playfield is a 10×9 grid and you are to move two colored pieces back to their original place after being scattered. The rule is you can only move a piece across one other piece of the opposite color, kinda like taking a piece in Checkers. To make things fair I decided that instead of giving the pieces random coordinates I would make the pieces move in accordance to the rules to ensure that the player could backtrack and the game was solvable.

As they were moving I noticed that they started ignoring the rules. Jumping over more than one, jumping over the same color, and/or jumping over empty spaces. I broke up the code to only move when I pressed a key and print the board array. The output ended up like this:

The array being printed each step taken

As you’ll notice on the last capture, a piece “clones” itself and jumps over an empty space. Visually the piece is no longer in the place it was, but in the array it is now in two places.

var MARBLES = {
    stage: 0,
    drawrect: 0,
    ball: [],
    curball: -1,
    slideDest: {x: 0, y: 0},
    // array board flipped on its side so that [x] can come before [y]
    board: [
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0]
    ]
};

function MARBLES_init()
{
    MARBLES.stage = 0;
    MARBLES.drawrect = 0;
    MARBLES.ball = [];
}
function MARBLES_update(timing)
{
    if(MARBLES.stage == 0)
    {
        ctx.drawImage(images[scenes["MARBLES"]][2].img, 240-MARBLES.drawrect,240-MARBLES.drawrect,160+MARBLES.drawrect*2,MARBLES.drawrect*2,
                            240-MARBLES.drawrect,240-MARBLES.drawrect,160+MARBLES.drawrect*2,MARBLES.drawrect*2);
        MARBLES.drawrect += timing;
        if(MARBLES.drawrect > 240 + timing)
        {
            MARBLES.stage = 1;
            ctx.drawImage(images[scenes["MARBLES"]][3].img, 32, 112);
            ctx.drawImage(images[scenes["MARBLES"]][4].img, 32, 320);

            MARBLES.ball.push(new class_Marble(2,4,2));
            for(var y = 3; y < 6; y++)
                MARBLES.ball.push(new class_Marble(3,y,2));
            for(var y = 2; y < 7; y++)
                MARBLES.ball.push(new class_Marble(4,y,2));
            for(var y = 2; y < 7; y++)
                MARBLES.ball.push(new class_Marble(5,y,1));
            for(var y = 3; y < 6; y++)
                MARBLES.ball.push(new class_Marble(6,y,1));
            MARBLES.ball.push(new class_Marble(7,4,1));

            MARBLES.stage = 1;
            setTimeout(function () { MARBLES.stage = 2; },1000);
        }
    }
    else if(MARBLES.stage == 2)
    {
        if(MARBLES.curball == -1)
        {
            var dir = -1;
            if(inkey > 1) // is set at onkeyup
            {
                MARBLES.curball = Math.floor(Math.random() * MARBLES.ball.length);
                var curlx = MARBLES.ball[MARBLES.curball].locx;
                var curly = MARBLES.ball[MARBLES.curball].locy;
                dir = Math.floor(Math.random()*8);
                if(MARBLES.ball[MARBLES.curball].c == 1) var opos = 2;
                if(MARBLES.ball[MARBLES.curball].c == 2) var opos = 1;
            }
            if(dir == 0 && curlx > 1 && curly > 1 && MARBLES.board[curlx-1][curly-1] == opos && MARBLES.board[curlx-2][curly-2] == 0)
            {
                MARBLES.slideDest.x = 168+((curlx-2)*42.20);
                MARBLES.slideDest.y = 49+((curly-2)*42.20);
                MARBLES.board[curlx][curly] = 0;
                MARBLES.board[curlx-2][curly-2] = MARBLES.ball[MARBLES.curball].c;
            }
            else if(dir == 1 && curlx < 9 && curly > 1 && MARBLES.board[curlx+1][curly-1] == opos && MARBLES.board[curlx+2][curly-2] == 0)
            {
                MARBLES.slideDest.x = 168+((curlx+2)*42.20);
                MARBLES.slideDest.y = 49+((curly-2)*42.20);
                MARBLES.board[curlx][curly] = 0;
                MARBLES.board[curlx+2][curly-2] = MARBLES.ball[MARBLES.curball].c;
            }
            else if(dir == 2 && curlx > 1 && curly < 8 && MARBLES.board[curlx-1][curly+1] == opos && MARBLES.board[curlx-2][curly+2] == 0)
            {
                MARBLES.slideDest.x = 168+((curlx-2)*42.20);
                MARBLES.slideDest.y = 49+((curly+2)*42.20);
                MARBLES.board[curlx][curly] = 0;
                MARBLES.board[curlx-2][curly+2] = MARBLES.ball[MARBLES.curball].c;
            }
            else if(dir == 3 && curlx < 9 && curly < 8 && MARBLES.board[curlx+1][curly+1] == opos && MARBLES.board[curlx+2][curly+2] == 0)
            {
                MARBLES.slideDest.x = 168+((curlx+2)*42.20);
                MARBLES.slideDest.y = 49+((curly+2)*42.20);
                MARBLES.board[curlx][curly] = 0;
                MARBLES.board[curlx+2][curly+2] = MARBLES.ball[MARBLES.curball].c;
            }
            else if(dir == 4 && curlx > 1 && MARBLES.board[curlx-1][curly] == opos && MARBLES.board[curlx-2][curly] == 0)
            {
                MARBLES.slideDest.x = 168+((curlx-2)*42.20);
                MARBLES.slideDest.y = 49+(curly*42.20);
                MARBLES.board[curlx][curly] = 0;
                MARBLES.board[curlx-2][curly] = MARBLES.ball[MARBLES.curball].c;
            }
            else if(dir == 5 && curlx < 9 && MARBLES.board[curlx+1][curly] == opos && MARBLES.board[curlx+2][curly] == 0)
            {
                MARBLES.slideDest.x = 168+((curlx+2)*42.20);
                MARBLES.slideDest.y = 49+(curly*42.20);
                MARBLES.board[curlx][curly] = 0;
                MARBLES.board[curlx+2][curly] = MARBLES.ball[MARBLES.curball].c;
            }
            else if(dir == 6 && curly > 1 && MARBLES.board[curlx][curly-1] == opos && MARBLES.board[curlx][curly-2] == 0)
            {
                MARBLES.slideDest.x = 168+(curlx*42.20);
                MARBLES.slideDest.y = 49+((curly-2)*42.20);
                MARBLES.board[curlx][curly] = 0;
                MARBLES.board[curlx][curly-2] = MARBLES.ball[MARBLES.curball].c;
            }
            else if(dir == 7 && curly < 8 && MARBLES.board[curlx][curly+1] == opos && MARBLES.board[curlx][curly+2] == 0)
            {
                MARBLES.slideDest.x = 168+(curlx*42.20);
                MARBLES.slideDest.y = 49+((curly+2)*42.20);
                MARBLES.board[curlx][curly] = 0;
                MARBLES.board[curlx][curly+2] = MARBLES.ball[MARBLES.curball].c;
            }
            else
            {
                MARBLES.curball = -1;
            }
        }
        else
        {
            if(MARBLES.ball[MARBLES.curball].px < MARBLES.slideDest.x)
                MARBLES.ball[MARBLES.curball].moveX(1);
            if(MARBLES.ball[MARBLES.curball].px > MARBLES.slideDest.x)
                MARBLES.ball[MARBLES.curball].moveX(-1);
            if(MARBLES.ball[MARBLES.curball].py < MARBLES.slideDest.y)
                MARBLES.ball[MARBLES.curball].moveY(1);
            if(MARBLES.ball[MARBLES.curball].py > MARBLES.slideDest.y)
                MARBLES.ball[MARBLES.curball].moveY(-1);
            if(MARBLES.ball[MARBLES.curball].px > MARBLES.slideDest.x-1 && MARBLES.ball[MARBLES.curball].px < MARBLES.slideDest.x+1 && MARBLES.ball[MARBLES.curball].py > MARBLES.slideDest.y-1 && MARBLES.ball[MARBLES.curball].py < MARBLES.slideDest.y+1)
            {
                PlaySound(scenes["MARBLES"],2,OPTIONS.volsfx,1);
                console.log("----------");
                for(var y = 0; y < 9; y++) // printing the array as shown above
                {
                    var t = "";
                    for(var x = 0; x < 10; x++)
                    {
                        t += MARBLES.board[x][y] + " ";
                    }
                    console.log(t);
                }
                MARBLES.curball = -1;
            }
        }
    }
}
function class_Marble(x,y,c)
{
    this.locx = x;
    this.locy = y;
    this.c = c;
    this.px = 168+(x*42.20);
    this.py = 49+(y*42.20);
    this.bkdata = ctx.getImageData(this.px,this.py,42,42);
    MARBLES.board[x][y] = c;
    ctx.drawImage(images[scenes["MARBLES"]][this.c-1].img, this.px,this.py);
    this.update = function(timing)
    {
        
    }
    this.setPos = function(px,py)
    {
        ctx.putImageData(this.bkdata,this.px,this.py);
        this.px = px;
        this.py = py;
        this.bkdata = ctx.getImageData(this.px,this.py,42,42);
        ctx.drawImage(images[scenes["MARBLES"]][this.c-1].img, this.px,this.py);
    }
    this.moveX = function(inc)
    {
        ctx.putImageData(this.bkdata,this.px,this.py);
        this.px += inc;
        this.bkdata = ctx.getImageData(this.px,this.py,42,42);
        ctx.drawImage(images[scenes["MARBLES"]][this.c-1].img, this.px,this.py);
    }
    this.moveY = function(inc)
    {
        ctx.putImageData(this.bkdata,this.px,this.py);
        this.py += inc;
        this.bkdata = ctx.getImageData(this.px,this.py,42,42);
        ctx.drawImage(images[scenes["MARBLES"]][this.c-1].img, this.px,this.py);
    }
}

How to create custom tailwind react components

I want to create a a library of custom components with specific tailwind stylings that are functionally the same as a standard react HTMLButton,. For example I want to create a element that has all of the same properties and functionality as a standard element (onClick, active, etc), but when it is rendered it is rendered with my custom styling without having to set the className property over and over on standard elements.

How do I go about this? I am struggling to wrap my head around React’s implementation of extending React.Component and the documentation states that method is deprecated now anyway

How to keep malicious users from inserting harmful code in a code sandbox? [closed]

I want to make a code sandbox for HTML, CSS, and JavaScript. But, I also want to keep my site as secure as possible, which would mean preventing malicious JS code from being added to the site. Even though my site is static, there are still harmful things someone could do with JS(like, downloading a virus to a user’s computer!). But, the idea of a code sandbox is to allow users to play around with code. Do I need to look up every single malicious JS function and put that in a filter? Or is there something I’m missing?

Next Js automatic refresh

I’m on a web application using nextJs and i want my page to refresh when there’s new data since the mobile.

Here is the page:

import { MaintenanceContractDataTable } from "@/components/maintenanceContractDataTable/data-table";
import { maintenanceContractColumns } from "@/components/maintenanceContractDataTable/maintenanceContractColumns";
import { buttonVariants } from "@/components/ui/button";

import { getMaintenanceContracts } from "@/services/maintenanceContract";
import { MaintenanceContractT } from "@/types/maintenanceContract";
import Link from "next/link";

const MaintenanceContracts = async () => {
  const maintenanceContracts: MaintenanceContractT[] =
    await getMaintenanceContracts();

  return (
    <section className="container w-[100%] bg-[#ffffff] p-3 space-y-3 rounded">
      <header className="flex justify-between items-center mb-10">
        <h6 className="text-3xl">Contrats de maintenances</h6>
        <Link
          href="maintenanceContract/addMContract"
          className={`${buttonVariants({
            variant: "default",
          })} bg-[#2264E5] text-white hover:bg-blue-400 hover:text-white`}
        >
          Créer un contrat de maintenance
        </Link>
      </header>
      <MaintenanceContractDataTable
        columns={maintenanceContractColumns}
        data={maintenanceContracts}
      />
    </section>
  );
};

export default MaintenanceContracts;

So i tried first to set cache to ‘no-store’ but it didn’t work and then the revalidate property in the server component but it still doesn’t work like this:

export const getMaintenanceContracts = async (): Promise<
  MaintenanceContractT[]
> => {
  const session = await getServerSession(authOptions);
  // console.log("getCities");
  const res = await fetch(`${baseUrl}/contratMaintenaces/`, {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${session?.user.access}`,
    },
    next: { revalidate: 3 },
  });
  // console.log("result get maintenance contract ", res);
  return res.json();
};

How to add WeakRef support to goja JavaScript engine in Go?

I’m using the goja JavaScript engine in my Go application and need to implement WeakRef support for my use case. Currently, when I try to use WeakRef in goja, it throws an error:

package main

import (
    "fmt"
    "github.com/dop251/goja"
)

func main() {
    vm := goja.New()
    
    _, err := vm.RunString(`
        let obj = {name: "test"};
        let weakRef = new WeakRef(obj);
        console.log(typeof weakRef);
    `)
    
    if err != nil {
        fmt.Println("Error:", err) 
        // Output: Error: ReferenceError: WeakRef is not defined
    }
}

According to the goja documentation, WeakRef and FinalizationRegistry are not implemented due to Go runtime limitations.

My questions:

  1. Is there a way to implement a custom WeakRef polyfill or native binding in goja?
  2. What are the specific Go runtime limitations that prevent WeakRef implementation?
  3. Are there any workarounds or alternative approaches to achieve weak reference functionality?
  4. Has anyone successfully implemented a WeakRef-like feature using goja’s extension capabilities?

What I’ve tried:

  1. Custom polyfill attempt:
vm.Set("WeakRef", func(call goja.FunctionCall) goja.Value {
    // This doesn't work properly because Go's GC 
    // doesn't provide weak reference semantics
    target := call.Argument(0)
    // How to create a weak reference here?
    return vm.NewObject()
})
  1. Using sync.Map with manual cleanup:
// This isn't truly "weak" - objects won't be GC'd automatically
var weakStore sync.Map

vm.Set("WeakRef", func(call goja.FunctionCall) goja.Value {
    id := generateID()
    weakStore.Store(id, call.Argument(0))
    
    obj := vm.NewObject()
    obj.Set("deref", func() goja.Value {
        if val, ok := weakStore.Load(id); ok {
            return val.(goja.Value)
        }
        return goja.Undefined()
    })
    return obj
})

Use case:

I’m building a JavaScript sandbox that needs to run code with WeakRef for memory management in long-running scripts. The scripts are user-provided and may rely on WeakRef for proper cleanup.

Environment:

  • Go 1.22
  • goja v0.0.0-20250624190929-4d26883d182a
  • Linux x86_64

Is there a proper way to implement WeakRef support in goja, or should I consider alternative JavaScript engines for Go?

Use Object.groupBy function to group by a variable [duplicate]

How can I use the Object.groupBy function with a variable?

For example:

const inventory = [ 
  { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
  { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" },
  { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" },
  { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" },
  { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },
  { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" },
  { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" },
  { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }
]

I would like to display data grouped by a single key, based on the user’s selection.

let key = 'Phase';
const result = Object.groupBy(inventory, ({ key }) => key);
console.log(result);

Current output:

{
  undefined: [
    { Phase: 'Phase 1', Step: 'Step 1', Task: 'Task 1', Value: '5' },
    { Phase: 'Phase 1', Step: 'Step 1', Task: 'Task 2', Value: '10' },
    { Phase: 'Phase 1', Step: 'Step 2', Task: 'Task 1', Value: '15' },
    { Phase: 'Phase 1', Step: 'Step 2', Task: 'Task 2', Value: '20' },
    { Phase: 'Phase 2', Step: 'Step 1', Task: 'Task 1', Value: '25' },
    { Phase: 'Phase 2', Step: 'Step 1', Task: 'Task 2', Value: '30' },
    { Phase: 'Phase 2', Step: 'Step 2', Task: 'Task 1', Value: '35' },
    { Phase: 'Phase 2', Step: 'Step 2', Task: 'Task 2', Value: '40' }
  ]
}

Expected output:

{
  Phase 1: [
    { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
    { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" },
    { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" },
    { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" }
  ],
  Phase 2: [
    { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },
    { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" },
    { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" },
    { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }
  ]
}