puppeteer with an async function, doesnt the scope of the variables [duplicate]

I have a test code with puppeteer, and I use some of page methods, such evaluate to run js on the page. The thing is, inside await page.evaluate(() => { }) my local scoped variables from node instances, as expectedly, cannot be accessed. I cannot access i or k for example, with page.evaluate() in the code below.

this is the exact error message Error [ReferenceError]: i is not defined at evaluate...

How can I use the variables in that scope ? or is there a different approach to doing this ? I am looping the alphabet for a test case with multiple for in each other.

const puppeteer = require('puppeteer');
const alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];


(async () => {
    const browser = await puppeteer.launch({ headless: false})
    const page = await browser.newPage()


    for(var i = 0; i < alphabet.length; i++){
        for(var j = 0; j < alphabet.length; j++){
            for(var k = 0; k < alphabet.length; k++){
                for(var l = 0; l < alphabet.length; l++){
                    
                    await page.evaluate(() => {  
                        document.querySelector('input[id="myId"]').value = alphabet[i] + alphabet[j] + alphabet[k] + alphabet[l];  
                    })
                } 
            } 
        }  
    }

})

Running into “Target page, context or browser has been closed” issue

The below code is my Playwright test function

    test("@Login @Testing Sign In Page Test", async ({ page }) => {
        console.log("Sign In Page Test");
 
        const pageManager = new pageObjectManager(page);
        const homePage = pageManager.getHomePage();
        const loginPage = pageManager.getLoginPage();
        const signInPage = pageManager.getSignInPage();

        // await homePage.goToHomePage();
        await page.goto("https://magento.softwaretestingboard.com/");

        // await loginPage.goToSignInPage();
        console.log(await page.title());
        await page.locator("//li[@class='authorization-link']").first().click();

        // await signInPage.validateLandingOnSignInPage();
        console.log(await page.title());
        await expect(page).toHaveTitle("Customer Login");
    });

This worked for me a few months ago but now, when I am trying to rerun the test case, I run into the below error

Error: page.title: Target page, context or browser has been closed

      34 |
      35 |      // await signInPage.validateLandingOnSignInPage();
    > 36 |      console.log(await page.title());
         |                             ^
      37 |      await expect(page).toHaveTitle("Customer Login");
      38 | });
      39 |

Even when I place the code in functions mentioned in comments just above them, I see the issue.

I am not sure what is causing this fresh issue. Please help me. Thanks in advance.

I tried to connect firebase to my chrome extension but It didn’t work

It showed this error:
Refused to load the script ‘https://gstatic.com/firebasejs/8.2.9/firebase-app.js’ because it violates the following Content Security Policy directive: “script-src-elem ‘self’ ‘unsafe-inline’ https://www.gsataic.com https://*.firebaseio.com https://www.googleapis.com”.
I build my chrome extension with manifest version 3,
Please help me !

I tried to add
“content_security_policy”: {
“extension_pages”: “script-src ‘self’ ‘wasm-unsafe-eval’ ; object-src ‘self’; script-src-elem ‘self’ ‘unsafe-inline’ https://www.gsataic.com https://*.firebaseio.com https://www.googleapis.com;”
}

to manifest.json but it still didn’t work

What is correct syntax to change the user password in an AD using NodeJs’s ldapts?

I know the password string must contain double quotes and must be UTF-16 encrypted.
So I have tried this way:

let passwdUtf16 = Buffer.from(""mypwd"", 'utf16le');

let change = new Change({ operation: 'replace', modification: new Attribute({ type: unicodePwd;binary', values: [passwdUtf16] }) });

await client.modify('cn=myusername,ou=MyOrg,ou=Organizations,dc=myproject,dc=local', change);

but I’m getting this error: {“code”:53,”name”:”UnwillingToPerformError”}

Am I getting something wrong in the syntax ? I’ve tried unicodePwd;binary, UnicodePwd;binary, unicodePwd, unicodePwd for type field with same results.

ldapts page: https://github.com/ldapts/ldapts

What am I doing wrong ?

Node.js and bracket notation when accesing json property

I’m creating a simple app using React and Vite,I’m accesing PokeAPI to fetch the pokemon data and after that I’m just mapping those objects by leaving only the props I want.Sadly,when I want to use the bracket notation to access the object’s proprty like this:

    image: pokemon.sprites.other["official-artwork"].front_default,

I get an error:

Uncaught (in promise) ReferenceError: artwork is not defined

and strangely,the code my browser is showing me looks like this:

      image: pokemon.sprites.other.official - artwork.front_default,

full context:

      pokemons = pokemons.map((pokemon) => ({
id: pokemon.id,
pokeName: pokemon.name,
image: pokemon.sprites.other["official-artwork"].front_default,
reactID: uuidv4(),

}));

Despite the errors I get the app is working.

Adding conditional logic just to check for Service Ops user, new to JavaScript and advice?

Stack Community. I have the code below. In short, it’s enabling and disabling fields on conditions.
Below works perfect.

function unLockNonSalaryCostFieldsBasedOnRolesTeams(executionContext) {
const formContext = executionContext.getFormContext();

const roles = ["Service Ops User", "DocuSignUser", "Geographic Enhanced User", "Support Business Advisor"];
// Store Security Roles

const userRoles = Xrm.Utility.getGlobalContext().userSettings.roles;

// Check if the user has any of the roles in the 'roles' array
const hasAnyRole = userRoles.get().some(r => roles.includes(r.name));

// Check specifically for the 'Support Business Advisor' role
const hasSupportBusinessAdvisorRole = userRoles.get().some(r => r.name === "Support Business Advisor");

const currentFundingStatus = formContext.getAttribute("fsdyn_fundingstatus").getValue();

const grantIntentionType = formContext.getAttribute("fsdyn_grantintentiontype").getValue();

// Ensure 'grantIntentionType' has a value before accessing [0]
const grantIntentionTypeLookUpValueName = grantIntentionType && grantIntentionType.length > 0 ? grantIntentionType[0].name : "";

if (grantIntentionTypeLookUpValueName !== "Post" && currentFundingStatus === FundingStatus.Proposed) {
    // Unlock or lock fields based on whether the user has any of the specified roles
    formContext.getControl("fsdyn_amount").setDisabled(!hasAnyRole);
    formContext.getControl("fsdyn_fundingperiodmonths").setDisabled(!hasAnyRole);

    // Specifically unlock 'activity code' if the user has the 'Support Business Advisor' role
    if (hasSupportBusinessAdvisorRole) {
        formContext.getControl("fsdyn_activitycode").setDisabled(false);
    } else {
        formContext.getControl("fsdyn_activitycode").setDisabled(true);
    }
} else {
    // Optionally, lock the fields if the main condition is not met
    formContext.getControl("fsdyn_amount").setDisabled(true);
    formContext.getControl("fsdyn_fundingperiodmonths").setDisabled(true);
    formContext.getControl("fsdyn_activitycode").setDisabled(true);
}}

I have a function unLockFieldsBasedOnConditions below as well. I want to combine it with the top function, but don’t want to break any functionality or regress anything.

    function unLockFieldsBasedOnConditions(executionContext) {
        const formContext = executionContext.getFormContext();
    
        const roles = ["Service Ops User"];
        //Store Security Roles
    
        const userRoles = Xrm.Utility.getGlobalContext().userSettings.roles;
        const hasRole = userRoles.get().some(r => roles.indexOf(r.name) != -1);
    
        const currentFundingStatus = formContext.getAttribute("fsdyn_fundingstatus").getValue();
    
        if (currentFundingStatus === FundingStatus.NotInFunding || currentFundingStatus === FundingStatus.Adopted) {
            formContext.getControl("fsdyn_hours").setDisabled(!hasRole);
            formContext.getControl("fsdyn_wte").setDisabled(!hasRole);
            formContext.getControl("fsdyn_wageband").setDisabled(!hasRole);
        }
    }

My question is: Should I add the logic of unLockFieldsBasedOnConditions to unLockNonSalaryCostFieldsBasedOnRolesTeams or should I leave them as separate functions?

Also, if I do add the logic, please advise how to combine without regressing?

Things I tried:

  1. Tried storing Service Ops User role in own variable.
  2. Added the if logic like above.

Code that didn’t work properly:

function unLockNonSalaryCostFieldsBasedOnRoles(executionContext) {
                const formContext = executionContext.getFormContext();

                // Store Security Roles
                const roles = ["Service Ops User", "DocuSignUser", "Geographic Enhanced User"];

                const userRoles = Xrm.Utility.getGlobalContext().userSettings.roles;

                // Check if the user has any of the roles in the 'roles' array
                const hasAnyRole = userRoles.get().some(r => roles.includes(r.name));

                // Check specifically for the 'Support Business Advisor' role
                const hasSupportBusinessAdvisorRole = userRoles.get().some(r => r.name === "Support Business Advisor");

                // Check specifically for the 'Service Ops User' role
                const hasServiceOpsUserRole = userRoles.get().some(r => r.name === "Service Ops User");

                const currentFundingStatus = formContext.getAttribute("fsdyn_fundingstatus").getValue();

                const grantIntentionType = formContext.getAttribute("fsdyn_grantintentiontype").getValue();

                // Ensure 'grantIntentionType' has a value before accessing [0]
                const grantIntentionTypeLookUpValueName = grantIntentionType && grantIntentionType.length > 0 ? grantIntentionType[0].name : "";

                if (grantIntentionTypeLookUpValueName !== "Post" && currentFundingStatus === FundingStatus.Proposed) {
                    // Unlock or lock fields based on whether the user has any of the specified roles
                    formContext.getControl("fsdyn_amount").setDisabled(!hasAnyRole);
                    formContext.getControl("fsdyn_fundingperiodmonths").setDisabled(!hasAnyRole);

                    // Specifically unlock 'activity code' if the user has the 'Support Business Advisor' role
                    if (hasSupportBusinessAdvisorRole) {
                        formContext.getControl("fsdyn_activitycode").setDisabled(false);
                    }

                    else {
                        formContext.getControl("fsdyn_activitycode").setDisabled(true);
                    }
                }
                else {
                    if (hasServiceOpsUserRole && currentFundingStatus === FundingStatus.NotInFunding || currentFundingStatus === FundingStatus.Adopted) {
                        formContext.getControl("fsdyn_hours").setDisabled(false);
                        formContext.getControl("fsdyn_wte").setDisabled(false);
                        formContext.getControl("fsdyn_wageband").setDisabled(false);
                    }
                }
            }
            ;

notifee.onBackgroundEvent only calls second time on iOS

I have implemented categories using Notifee.setNotificationCategories

    {
      id: 'actions',
      actions: [
        {
          id: 'yes',
          title: 'Yes',
        },
        {
          id: 'no',
          title: 'No',
        },
        {
          id: 'reply', // Action with input
          title: 'Reply',
          input: {
            placeholder: 'Type your reply here...', // Placeholder text for input field
            buttonText: 'Send', // Text for the action button
          },
        },
      ],
    },
  ]);

I need to call an API once the user types something in text box and clicks on reply

notifee.onBackgroundEvent(({type, detail}) => {
if (detail.pressAction.id === 'reply') {
  const userInput = detail.input; // This is the input text entered by the user
  console.log('User input:', userInput);
  postData(userInput, detail.notification.data.conversation_id);//api call
}
});

in the above function postdata should call an API with user input

It only works the second time if the app is in a quit state. How can I make it work on the first notification?
I think the app is possibly being woken up by the first notification in the background, and it works on the second notification because the app was already woken up by the first one.

Copy response from Chrome Dev tools network tab

I am working with Typescript React.I want to copy paste a response into my react code as a mock-file.But when I copy from Network tab, the JSON response’s keys are in double quotes.I want to convert this JSON response to a pure JavaScript object so that folding and unfolding works in my vs code.
Refer the response below

When I copy this to vs code into my mock.ts file
enter image description here

I want the JSON in below format.(The double quotes of keys are removed)
enter image description here

How can I do this without manually editing/removing the double quotes?

How subscribe a Web push Protocol with JS on a PWA on iOS

I received a commission for a PWA that uses the Web push Protocol for receives notifications from the server.

The PWA is in WASM, with Blazor .NET 8. I used JS for the entire Web push architecture. The PWA works well on Android, Windows, Apple and iOS.

But I have a big problem implementing Web Push Protocol notifications on iOS > 16.4 version.

From what I understand you must have an Apple development license – which I have -. But I don’t understand if I have to create keys and certificates for an iOS app that I will not use (I have my blazor PWA) and how to connect in JS to which server, for receive the token of the subscription.

I only find references to make native Apps in iOS, but nothing that can help me if the app comes from a world outside iOS.

Someone can help me to manage Web Push Protocol with JS script in iOS ?

Thanks a lot.

How to send a status code on RESTful controller api without an error?

VM1411:1 Uncaught (in promise) SyntaxError: Unexpected token ‘O’, “OK” is not valid JSON

When I fetch JSON(stringified object) data to the server and try to send a statusCode number 200 for indicating its status as OK in order to response, the client webpage keeps receiving that error for unknown reason. The server “can” take the JSON from the client-side, but only retrieving does not working right now. How to send the status code without getting an error?

client/js/product/index.js

var lotion = {
    name: "Vaseline",
    price: 20,
    skinProtection: true,
    protectionLevel: 10
};

class Order {
    constructor(method, target) {
        this.method = method;
        this.target = target;
        this.serve();
    }
    options(method, target) {
        return {
            method: method,
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(target)
        }
    }
    readAPI(path) {
        return fetch(`http://localhost:3500/controllers/product/${path}`, this.options(this.method, this.target))
    }
    async serve() {
       let receive = await (await this.readAPI('order')).json();
       console.log(receive);
    }
}

let getOrder = new Order('post', lotion)

server/app/controllers/index.js

const express = require('express');
const controllers = express.Router();

controllers.post('/product/order', async (req, res) => {
    console.log(req.body);
    res.sendStatus(200); // This causes that the browser receives an error
})

module.exports = controllers; // all the name must be matched

server/app/app.js

require('dotenv').config();

const express = require('express');
const cors = require('cors');
const path = require('path');

const app = express();
app.use(cors());
app.use(express.json());

const controllers = require('./controllers/index.js');
app.use('/controllers', controllers)

module.exports = app;

server/index.js

const app = require('./app/app.js');

app.listen(process.env.PORT, () => {
    console.log(`port: ${process.env.PORT}`);
})

File structure diagram

.
├── client/
│   ├── js/
│   │   ├── index/
│   │   └── product/
│   │       └── index.js
│   └── pages/
│       ├── index.html
│       └── product.html
└── server/
    ├── app/
    │   ├── controllers/
    │   │   └── index.js
    │   └── app.js
    ├── .env
    ├── node_modules
    ├── index.js
    ├── package-lock.json
    └── package.json

Attempts

  1. Added `”Accept”: “application/json” to as a headers’ property.
  2. Added .json({message: "OK"}) on res.sendStatus(200).

Developer tools inspection tool is dangerous? [duplicate]

Imagine the following scenario: “I’m running inspect on a javascript file that’s not mine. I edit the onclick event of a button to send to database spam sql quesries, such as “insert into table values…”.” Is this possible? I’m not asking because I want to become a cyberbully, I’m actually building a website that communicated with a server and the server hosts a database. Could this scenario be possible, because of the inspect tool? If yes, how can I prevent it?

Can I set the font-size to the maximum value the container can contain without overflow?

I have different containers of different sizes and they are all dynamic in size.

All containers have text inside them.

I want all text in all containers to be at the maximum font size the container can support without overflow.

I tried a bunch of calculation and clamp properties.

I tried to use ch measurements but they require a non-trivial calculation into the number of lines the text would be split into and is further complicated with word breaks.

I tried using JavaScript to achieve this, and more or less did so. However my JS solution loops over every such element and increases their text size until they overflow, or if they overflow decreases their font size until it no longer overflows, in in/decrements of 1px. However this does not scale to 100s of containers.

Creating and using dynamic variables based on a dynamic component

I have a table as a component, and now I am trying to build a column wise search within it.
The table that will be created will have a dynamic number of columns. Hence I need to create multiple variables for binding with the search input. I was trying to create those variables with eval (unsuccessfully, because I cannot use eval with svelte functionalities like writable or $:).

Note: the main restrictions I have are,

  1. the the dynamic variable has to be declared as writable(”)
  2. create columns has to be in a function (as I have to recreate them for other conditions), but the search columns needs to be outside the function, as it will be used across the page
  3. the number of total columns and the number of searchable columns are dynamic
  4. the full functionality is much more huge and complex, hence shared a small part of it, where I need some support

Note: Doing first time front end development, coming from Mainframes backend dev.

I have tried to replicate my scenario in the below repl (not working.. but you will get gist):
https://svelte.dev/repl/42335b2b121a402da1c5cd6c826bb5df?version=4.2.19

Expectation:
Need the value from any of those inputs to $searchColumn and the corresponding column value. Based on this I will use it to perform next set of tasks. Please see a working version of the scenario but with static defined variables:
https://svelte.dev/repl/fa3bd4c83d53421ea0eb3ae5936b401c?version=4.2.19

Angular: when should I use signals?

I am using signals in Angular 18 for small local states. But I don’t understand why and when I should use them instead of a normal class member. Let’s take a simple toggle:

Example 1

@Component({...})
export class ToggleComponent {
  toggleState: boolean = false;

  toggle() {
    this.toggleState = !this.toggleState;
  }
}

Example 2

@Component({...})
export class ToggleComponent {
  toggleState = signal(false);

  toggle() {
    this.toggleState.set(!this.toggleState());
  }
}

For this example: is there a real difference between those 2 approaches? Why should I use one and not the other? Given for example a parent and a child, and this child has a button which has the job to change the parent state, would be useful to use signal or whatelse?

How to Change the Default Background of bodySegmentation-mask-body-parts in p5.js?

I’m trying to change the background behind the detected body segment, but I can’t get it to work. Even though I’m modifying the background(...) function, it keeps defaulting to white. Can anyone explain why this is happening?

This is the link to the file I am working on :
https://editor.p5js.org/speedyonion/sketches/X9mwX9XB9

let bodySegmentation;
let video;
let segmentation;

let options = {
  maskType: "parts",
};

function preload() {
  bodySegmentation = ml5.bodySegmentation("BodyPix", options);
}

function setup() {
  createCanvas(640, 480);
  // Create the video
  video = createCapture(VIDEO);
  video.size(640, 480);
  video.hide();

  bodySegmentation.detectStart(video, gotResults);
}

function draw() {
  background(0,0,0);
  image(video, 0, 0);
  if (segmentation) {
    image(segmentation.mask, 0, 0, width, height);
  }
}

// callback function for body segmentation
function gotResults(result) {
  segmentation = result;
}