Selectively run inline scripts after blocking all of them in FIrefox

Context: NoScript blocks inline scripts by using a content security policy.

Is it possible, for a Firefox extension, to walk the DOM and selectively pick out scripts to allow, after blocking all of it with a CSP?

For example, walking the DOM to remove disallowed scripts, then somehow making Firefox execute all the remaining scripts?

I’m not sure how to execute these scripts in the context of the page rather than in the context of the extension.

Is it possible to set a default value for an Material React Table with a select

I am trying to make a table with Material UI Table, and when I edit or add a row some values are to be selected from a dropdown. That works as expected, but I would like to have one of the dropdown values as a default when creating a new row, instead of just being an empty value as it is now.

This is my table

    const table = useMaterialReactTable({
        data: data ?? [],
        columns: useMemo(() => [
            {
                header: 'Name',
                accessorKey: 'name',
                editable: 'onAdd',
                width: 200,
                muiEditTextFieldProps: {
                    placeholder: 'Name'
                }
            },
            {
                header: 'Dropdown',
                accessorKey: 'dropdown',
                editVariant: 'select',
                editSelectOptions: dropdown_values,
                filterVariant: 'select',
                filterSelectOptions: dropdown_values,
                muiEditTextFieldProps: {
                    value: staff_department
                },
                width: 200,
            },
           ], [dropdown_values]),
        createDisplayMode: 'row',
        editDisplayMode: 'row',
        enableEditing: true,
        onCreatingRowSave: async ({ table, values }) => {
             await createNewRow(values);
             table.setCreatingRow(false);
        },
        onEditingRowSave: async ({ table, row, values }) => {
                await updateRow({...row.original, ...values});
        },
        renderRowActions: ({ row, table }) => (
            <TableRowControls
                onEdit={ () => table.setEditingRow(row) }
            />
        ),
        displayColumnDefOptions: {
            'mrt-row-actions': {
                visibleInShowHideMenu: false
            }
        },
        enableDensityToggle: false,
        enableFullScreenToggle: false,
        state: {
            density: 'compact'
        },
        renderTopToolbarCustomActions: ({ table }) => (
            <div>
                <CreateButton onClick={ () => table.setCreatingRow(true) }/>
            </div>
        ),
    });

Is it possible to add a defaultValue for the dropdown?

Thanks for helping

Qualtrics – error in getting values from question

I am attempting to write a survey which will provide experimental vignettes to participants based on previous ratings of political parties. Obviously, this means that I’ll need to pipe results from previous questions to a new question. I’ve tried to do this with a matrix table, but that has led to the following error:

SE API Error:  TypeError: Cannot read properties of null (reading 'val')
    at A.i.eval (eval at <anonymous> (jfeLib.fa2484b7040929bdf0ac.min.js:2:125561), <anonymous>:25:56)
    at A.i.<anonymous> (jsApi.8c8dd06a862b12e2d92e.min.js:1:5034)
    at A.i.r (jfeLib.fa2484b7040929bdf0ac.min.js:2:29148)
    at A.i.s (jfeLib.fa2484b7040929bdf0ac.min.js:2:29191)
    at s (jfeLib.fa2484b7040929bdf0ac.min.js:2:28405)
    at A.i._trigger (jfeLib.fa2484b7040929bdf0ac.min.js:2:30008)
    at A.i.r [as _trigger] (jfe.e7b329a67c066949aeb4.min.js:2:368934)
    at A.i._finishRenderAndTriggerReady (jfe.e7b329a67c066949aeb4.min.js:2:283139)
    at A.i.r [as _finishRenderAndTriggerReady] (jfe.e7b329a67c066949aeb4.min.js:2:368934)
    at A.i.__postRender (jfe.e7b329a67c066949aeb4.min.js:2:263578) ƒ () {   var matrixQuestionID = "QR~QID22~"; 
    var partyNames = [
        "Party A", "Party B", "Party C", "Party D", "Party E", "Party F", "Party G"
    ];

var ratings = [];

For reference, this is the code I’ve written in the matrix table JavaScript:
Qualtrics.SurveyEngine.addOnUnload(function()

Qualtrics.SurveyEngine.addOnUnload(function()
{
    var matrixQuestionID = "QR~QID22~"; 
    var partyNames = [
        "Party A", "Party B", "Party C", "Party D", "Party E", "Party F", "Party G"
    ];
    
    var ratings = [];
    
    // Capture Ratings
    for (var i = 0; i < partyNames.length; i++) {
        var rating = parseInt($(matrixQuestionID+(i+1)).val());
        ratings.push({ party: partyNames[i], rating: rating });
    }

    // Sort ratings
    ratings.sort(function(a, b) {
        return b.rating - a.rating;
    });

    // Store ordered parties
    for (var j = 0; j < ratings.length; j++) {
        Qualtrics.SurveyEngine.setEmbeddedData("SortedParty_" + (j + 1), ratings[j].party);
    }

});

I’m certain that it’s due to the naming of the question, but I can’t figure out how to fix it (I have tried QID22, QR~QID22~ (to match the HTML name), and the name that I gave it in Qualtrics, partyRank). Any help would be great!

Error : Cannot set properties of null when using recaptcha

I have two domains, a.com and b.com, both with reCAPTCHA enabled. I’m using the same codebase for both websites, but the reCAPTCHA implementation works on a.com but not on b.com. Here’s the setup:

a.com: The reCAPTCHA keys were created by a friend 2 years ago. I believe the keys are for reCAPTCHA v3, as the site uses grecaptcha.execute.

b.com: The reCAPTCHA keys were created today, and I used reCAPTCHA v3 for this domain as well.

On b.com, I get an error:

contact.php:37 Uncaught (in promise) TypeError: Cannot set properties of null (setting 'value')
    at contact.php:37:71
(anonymous) @   contact.php:37
Promise.then        
then    @   recaptcha__en.js:591
(anonymous) @   contact.php:36
Promise.then        
(anonymous) @   recaptcha__en.js:138
(anonymous) @   recaptcha__en.js:195
(anonymous) @   recaptcha__en.js:196
(anonymous) @   recaptcha__en.js:472
(anonymous) @   recaptcha__en.js:196
(anonymous) @   recaptcha__en.js:1132
(anonymous) @   recaptcha__en.js:1142

Here’s the client-side code I’m using:

<script src="https://www.google.com/recaptcha/api.js?render=mysitekey"></script>
<script>
    grecaptcha.ready(function() {
        grecaptcha.execute('mysitekey', {action: 'contact_form'})
            .then(function(token) {
                document.getElementById('g-recaptcha-response').value = token;
            });
    });
</script>

Also I noticed that the reCAPTCHA tokens generated for the two domains have different lengths:

For a.com, the token is about 1100 characters.

For b.com, the token is around 2400 characters.

Can someone tell me what is wrong with this code?

Can i get multer to parse an array of strings in formdata as an array, and not as a comma seperated string?

I am using axios to send a FormData object, containing a categories field, an array of strings, to an express server. I am using multer to parse the FormData recieved, however req.body.categories is a single string after parsing eg ‘cat1, cat2, cat3’, not an array of strings eg [‘cat1’, ‘cat2’, ‘cat3’]

This is the code i am using to send the FormData:

newProduct: {categories: string[]}

const formData = new FormData()

for (let key of Object.keys(newProduct)){
  formData.append(key, newProduct[key])
}

const response = await axios.post('/api/products', formData)

I have tried to JSON.stringify(categories) before appending this to the formdata but multer understandably just parsed this as a string aswell.

It feels ‘icky’ to just use categories.split('') after multer has parsed the rest of the formdata so graciously for me, but is there another way or am i doing something wrong?

Using Pipe in No Standalone component

I have a no standalone component with Angular 19

import { Component, inject, OnInit } from '@angular/core';
import { HelloWorldFacade } from './+state/hello-world.facade';
import { Observable } from 'rxjs';
import { CommonModule, DatePipe } from '@angular/common';

@Component({
  selector: 'lib-hello-world-with-ngrx',
  standalone: false,
  template: `
      {{message$ | async}}
  `,
  styles: ``
})
export class HelloWorldWithNgrxComponent implements OnInit{

  public message$?: Observable<string>;
  private hwFacade = inject(HelloWorldFacade);


  ngOnInit(): void {
    this.message$ = this.hwFacade.message$

    setInterval(() => {
      this.hwFacade.appendMessage('a');
    }, 10000);
  }

}

with its module

import { CommonModule, AsyncPipe } from '@angular/common';
import { NgModule } from '@angular/core';
import { EffectsModule } from '@ngrx/effects';
import { StoreModule } from '@ngrx/store';
import { HelloWorldEffects } from './+state/hello-world.effects';
import { HelloWorldFacade } from './+state/hello-world.facade';
import * as fromHW from './+state/hello-world.reducer';
import { HelloWorldWithNgrxComponent } from './hello-world-with-ngrx.component';

@NgModule({
  imports: [
    CommonModule,
    AsyncPipe,
    StoreModule.forFeature(
      fromHW.HW_FEATURE_KEY,
      fromHW.hwReducer
    ),
    EffectsModule.forFeature([HelloWorldEffects])
  ],
  providers: [HelloWorldFacade],
  declarations: [HelloWorldWithNgrxComponent],
  exports: [HelloWorldFacade, HelloWorldWithNgrxComponent, CommonModule]
})
export class HelloWorldWithNgrxModule { }

I created a Workspace No Application, only for generate my personal lib

When i try to build the lib with comand ng build hello-world-with-ngrx i recive this error

✖ Compiling with Angular sources in Ivy partial compilation mode.
projects/hello-world-with-ngrx/src/lib/hello-world-with-ngrx.component.ts:10:20 - error NG8004: No pipe found with name 'async'.

Link for repo:
https://github.com/giolongo/gle-angular-lib/tree/master/projects/hello-world-with-ngrx/src/lib

How can i resolve it issue?

Mustache template with Jest

I am currently testing document printing on client side with jest (so test env is js-dom). And I stumbled upon error with lambda that is passed to template.
Heres the example of my code:

    const data = {
        ...someFields,
        someField: () => (text, render) => functionThatParsesText(render(text)),
    };

And jest throws error:

TypeError: render is not a function

Is it because Jest tries to call for a function in this code? If thats so, how can it be prevented?

Is there a way to stop rerendering the child components

I have created a simple component to show my problem,

"use client";

import { useEffect, useMemo, useState, memo } from "react";

import "./App.css";
import ChildComponent from "./components/child-component";
import Child2 from "./components/child2";

function App() {
  const [counter, setCounter] = useState(0);

  return (
    <div>
      <button onClick={() => setCounter(counter + 1)}>
        Counter is {counter}
      </button>
      <ChildComponent />
      <Child2 />
    </div>
  );
}

export default App;

The ChildComponent

import { memo } from "react";

const ChildComponent = () => {
  console.log("child renders");
  return <button>Click me</button>;
};

export default memo(ChildComponent);

The Child2 component

const Child2 = () => {
  console.log("child 2 rerenders");
  return <div>HIii theere</div>;
};

export default Child2;

Now the problem is every time I click on the counter button I see the console log as child renders which is from the ChildComponent and child2 rerenders which is from the Child2 component, which suggests to me anytime the parent component has some change it rerenders the child, how can I solve this issue.

PS – I have tried using memo and callback but haven’t found a potential solution.

VSCode: Drag and drop from OS file explorer to Custom Tree Item

I’m developing an extension for VSCode and I want to support drag and drop from OS File Manager to a custom tree view.

It works fine from VSCode File view to my custom Tree View. Here the code:

        const treeView = vscode.window.createTreeView(this.provider.getViewID(), {
        treeDataProvider: this.provider,
        canSelectMany: false,
        dragAndDropController: {
            handleDrag: (
                source: readonly vscode.TreeItem[],
                dataTransfer: vscode.DataTransfer,
                _token: vscode.CancellationToken
            ) => {
                console.log(source);
                console.log(dataTransfer);
            },
            handleDrop: (
                target: vscode.TreeItem | undefined,
                dataTransfer: vscode.DataTransfer,
                _token: vscode.CancellationToken
            ) => {
                console.log(target);
                console.log(dataTransfer);
            },
            dropMimeTypes: ['text/uri-list'],
            dragMimeTypes: ['text/uri-list'],
        },
    });

But It doesn’t work when I drag and drop from Filesystem Manager:

enter image description here

How to close stream with server-side event using fetch?

so I’m using server-side events to push messages from the server to the frontend. For front end. I’m using fetch to start the stream, like this

const response = await fetch(`${API_URL}/hello`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': api.defaults.headers.common['Authorization'],
      'Accept': 'text/event-stream',
    },
    body: JSON.stringify(input)
  });

  if (!response.ok) {
    const errorBody = await response.json();
    throw new Error(`generateImage HTTP error! status: ${response.status} ${response.statusText}. Details: ${JSON.stringify(errorBody)}`);
  }

  const reader = response.body.getReader();
  const decoder = new TextDecoder();
// everything else the same

How do we close the stream if using fetch? Currently I’m using AbortController but I don’t think it’s the best practice. Also every time the steam closes, an error will appear on the console log, which is not very nice.

FYI, I used fetch instead of Axios because Axios does not support event stream on Safari and I don’t use EventSource either because EventSource only works with GET request, while my server expose a POST request, and I cannot change that.

integrating native web components in Vue: properties are not reactive

I’m trying to integrate a vanilla js web component in Vue. The code is super contrived and just renders a name and surname as a proof of concept.

class HelloWorld extends HTMLElement {
    
  static observedAttributes = ["name", "surname"];

    constructor() {
      super();
    }
    
    connectedCallback() {
    const 
    shadow = this.attachShadow({ mode: 'closed' }),
    hwMsg = `Hello ${ this.name } ${ this.surname }`;
  
    shadow.append(hwMsg);  
  }
  
  // attribute change
  attributeChangedCallback(property, oldValue, newValue) {
    console.log('property ', property, ' changed from ', oldValue, ' to ' newValue);
    if (oldValue === newValue) return;
    this[ property ] = newValue;
    }
}
  
  customElements.define('hello-world', HelloWorld);

I registered the hello-world tag as custom in my vite.config file:

export default defineConfig({
  plugins: [
      vue({
        template: {
          compilerOptions: {
            isCustomElement: (tag) => tag.includes('hello-world')
          }
        }
      })
      ...]

I am including the webcomponent in the component where I want to use it:

<script setup lang="ts">
import '@/web_components/prova_web';
import { ref } from 'vue';

const name = ref('John');
const surname = ref('Smith');
</script>
<template>
  <main class="main-view">
    <form>
    <input id="model_name" v-model="name"/>
    <input  id="model_surname" v-model="surname">
   </form>
    Current values: {{ name }} {{ surname }} <br/>
    <hello-world :name="name" :surname="surname"></hello-world>
  </main>
</template>
<style scoped>
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.5.4/vue.global.min.js"></script>

The code renders just fine the first time, and the attributeChangedCallback is correctly called for both properties:

console log

Unfortunately, when I change a property using the form inputs, the attributeChangedCallback is not firing again, even though the property values have changed (and properly re-rendered above the custom tag).
Screenshot

It’s weird that the first time the ref value is correctly unpacked but subsequent changes to the refs’ values are not recognized as such. Can I achieve reactive property binding with plain javascript or am I forced to use a framework? (Lit seems very popular).