Html not loaded even after window.addEventListener(‘load’, do_something) is invoked

I’m working on a browser extension that scrapes data from a webpage. I’ve added a method to scrape data, which is invoked via a load listener:
window.addEventListener('load', scrapeSomething)
However, when I refresh the page and put a breakpoint in the Chrome Developer Tools, I notice that the HTML is still not fully loaded when the method is invoked. For instance, the HTML content at the time of invocation is just:
<div id="hiddenFrame"></div>

To mitigate this issue temporarily, the previous code had a 5-second delay before running the scraping logic:

let callDebouncer = () => {
setTimeout(() => {
//scraping part
},5000);  };
window.addEventListener('load', callDebouncer);

I want to avoid using a fixed delay and instead rely on a listener to ensure the page is fully loaded before scraping. Is there an alternative way to achieve this?

Jest – react-native-color-matrix-image-filters/dist/CMIFColorMatrixImageFilterNativeComponent.js: Could not find component config for native component

I have a React Native Android project and I just upgraded the react-native version from 0.72.3 to 0.74.3. After a fair amount of library upgrading, TS and Lint fixes, etc I was able to get my application to build and run fine.

Unfortunately, when I run my Jest tests I keep getting the following error:

/Users/user/Desktop/Projects/react-native/node_modules/react-native-color-matrix-image-filters/dist/CMIFColorMatrixImageFilterNativeComponent.js: Could not find component config for native component

I was also getting this error in Metro as I was trying to open the application when I wasn’t on the latest version of react-native-color-matrix-image-filters. Like I mentioned earlier, if I add the latest version, my app builds and runs fine, just that the tests are failing.

I tried deleting node_modules, yarn.lock, yarn install again but it still gives me that error when I run the tests. Anyone that might have an idea why is this happening?

Stripe Connect Payouts API

I am creating an application in which users can add their bank accounts in the application and from admin side I want to send the payouts to their bank accounts. I am using Node.js and Stripe.js (In Test Mode). Please anyone help me to fix this issue.

router.get("/testing-stripe", async (_, res) => {
  try {
    // Create a Stripe express account
    const account = await stripe.accounts.create({
      type: "express",
      country: "US",
      email: "[email protected]",
      business_type: "individual",
      individual: {
        first_name: "Hammad",
        last_name: "Umar",
      },
      capabilities: {
        card_payments: { requested: true },
        transfers: { requested: true },
      },
    });

    // Create a bank account token
    const token = await stripe.tokens.create({
      bank_account: {
        country: "US",
        currency: "usd",
        account_holder_name: "Hammad Umar",
        account_holder_type: "individual",
        routing_number: "110000000",
        account_number: "000123456789",
      },
    });

    // Attach the bank account token to the Custom account
    const bankAccount = await stripe.accounts.createExternalAccount(
      account.id,
      {
        external_account: token.id,
      }
    );

    // Generate onborading link
    const accountLink = await stripe.accountLinks.create({
      account: account.id,
      refresh_url: "http://localhost:5002/redirect",
      return_url: "http://localhost:5002/redirect",
      type: "account_onboarding",
    });

    const payout = await stripe.payouts.create(
      {
        amount: 5 * 100,
        currency: "usd",
        destination: bankAccount.id,
        source_type: "bank_account",
      },
      {
        stripeAccount: account.id,
      }
    );

    return res.json({
      url: accountLink.url,
      bankAccountId: bankAccount.id,
      stripeAccountId: account.id,
      payout,
    });
  } catch (error) {
    console.error("Error creating bank token:", error);
    return res.status(500).json({ message: error.message });
  }
});

The only issue with this snippet

 const payout = await stripe.payouts.create(
      {
        amount: 5 * 100,
        currency: "usd",
        destination: bankAccount.id,
        source_type: "bank_account",
      },
      {
        stripeAccount: account.id,
      }
    );

When I hit this API endpoint I got this error.

{
"message": "You have insufficient funds in your Stripe account for this transfer. Your ACH balance is too low.  You can use the /v1/balance endpoint to view your Stripe balance (for more details, see stripe.com/docs/api#balance)."
}

I also tried top-up / create charge API for trying add funds in my balance but in vein.

req.headers.authorization is undefined

So I’ve been trying to implement JWT authorization for my project, and there’s this specific step that I’ve been stuck for hours… So I have a middleware setup to try and verify the access token which is given when the user successfully logs in, and when I grab the token from the authorization header using this line: const authHeader = req.headers.authorization it’s always undefined. I tried watching more videos and they literally do the same but it always works fine on their part, they are able to grab the token and the further verify it, but here I am just following every step they do but its “UNDEFINED” 🙁

This is the code that verifies the credentials of the user and once its successful, it generates a refresh token that will be stored on the user’s cookies, and an access toke which will be sent as a json object.

the jwt object in my code is from jsonwebtoken library.

export async function verifyLogin(req, res) {
  const { username, password } = req.body;
  const foundUser = await findUsername(username);
  if (!foundUser) {
    return res.status(401).json({ invalidUsername: "Username not found" });
  }

  const passwordMatch = await bcrypt.compare(password, foundUser.password);
  if (!passwordMatch) {
    return res.status(401).json({ invalidPassword: "Invalid Password" });
  }

  const accessToken = jwt.sign(
    { id: foundUser.librarian_id },
    process.env.ACCESS_TOKEN_SECRET,
    { expiresIn: "100s" }
  );
  const refreshToken = jwt.sign(
    { id: foundUser.librarian_id },
    process.env.REFRESH_TOKEN_SECRET,
    { expiresIn: "1d" }
  );

  await insertRefreshToken(foundUser.librarian_id, refreshToken);

  res.cookie("jwt", refreshToken, {
    httpOnly: true,
    maxAge: 24 * 60 * 60 * 1000,
  });

This is the middleware to verify the token

export function verifyToken(req, res, next) {
  const authHeader = req.headers.authorization; //THIS LINE IS THE PROBLEM
    
  //const authHeader = req.headers['authorization']
  //some tutorials do this instead, and it still doesn't work in my code

  //next-step (check the token, if it exists split it...)
  //this part is not yet implemented

  try {
    const decoded = jwt.verify(token, process.env.ACESS_TOKEN_SECRET);
    req.id = decoded.id;
    next();
  } catch (error) {
    res.clearCookie("jwt");
    res.redirect("/login");
  }
}

And this is one of the routes that uses uses that middleware

app.get("/information", verifyToken, (req, res) => {
  res.render("info.ejs");
});

I tried getting the token this way
const token = req.cookies.jwt;

I mean it works but it gets the refresh token anyway since that was the token that was stored on the browser, but what I’m trying to get was the accessToken sent as json object.

@iFrame-resizer/react implementation error – Uncaught SyntaxError: Unexpected token ‘s’, “scroll-to-top” is not valid JSON

I am using the latest version of iframe-resizer/react for automatically adjusting the height and width of the iframe.
Whenever I’m reacting the content, I’m getting a runtime error stating –
VM2860:1 Uncaught SyntaxError: Unexpected token ‘s’, “scroll-to-top” is not valid JSON

I don’t know from where this is coming.
I have checked the events that are coming iframe. There also, nothing called scroll-to-top is mentioned.

Below is the code snippet I have written.
Please help me to solve this issue.

import IFrameResizer from "@iframe-resizer/react";
<IFrameResizer
          src={iframeSrc}
          license="GPLv3"
          className="iframe-dialog"
          title="Iframe Dialog"
          onLoad={onLoad}
          scrolling={false}
          forwardRef={iframeRef}
          style={{
            width: "100%",
            border: "none",
            opacity: "100",
            height: "100vh",
          }}
 />

I have tried onResized, onMessage handlers given in iframe-resizer/react to get the message, but still nothing happened.

The input in searchbar disappears when i click on any other space/part of the browser of when i click tab button

import React, { useState, useEffect, useRef } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import Autocomplete from "@mui/material/Autocomplete";
import TextField from "@mui/material/TextField";
import parse from "autosuggest-highlight/parse";
import match from "autosuggest-highlight/match";

const Input = () => {
  const [airports, setAirports] = useState([]);
  const [filteredAirports, setFilteredAirports] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [inputValue, setInputValue] = useState("");
  const [selectedValue, setSelectedValue] = useState(null);
  const navigate = useNavigate();
  const inputRef = useRef(null);

  useEffect(() => {
    async function fetchData() {
      setIsLoading(true);
      try {
        const res = await axios.get(`http://127.0.0.1:8000/airports`);
        const { data } = res;
        const options = data.map(d => ({
          value: `${d.name} (${d.code})`,
          label: `${d.name} (${d.code})`,
          name: d.name,
          code: d.code,
          id: d.id,
        }));
        setAirports(options);
      } catch (error) {
        console.error("Error fetching airports from backend's MongoDB. Check backend server connection:", error);
      } finally {
        setIsLoading(false);
      }
    }
    fetchData();
  }, []);

  const handleInputChange = async (event, newInputValue) => {
    setInputValue(newInputValue);
    if (newInputValue.length >= 3) {
      console.log(`Keystroke logged: ${newInputValue}`);
      const filtered = airports.filter(airport => 
        airport.name.toLowerCase().includes(newInputValue.toLowerCase()) ||
        airport.code.toLowerCase().includes(newInputValue.toLowerCase())
      );
      setFilteredAirports(filtered);

      try {
        const res = await axios.get(`http://127.0.0.1:8000/search/airport?search=${newInputValue}`);
        const { data } = res;
      } catch (error) {
        console.error("Error fetching airport data:", error);
      }
    } else {
      setFilteredAirports([]);
    }
  };

  const handleSubmit = e => {
    e.preventDefault();
    if (selectedValue) {
      navigate("/details", { state: { searchValue: selectedValue } });
    }
  };

  const handleBlur = () => {
    if (inputRef.current) {
      inputRef.current.setAttribute('data-value', inputRef.current.value);
    }
  };

  const handleFocus = () => {
    if (inputRef.current) {
      const storedValue = inputRef.current.getAttribute('data-value');
      if (storedValue) {
        inputRef.current.value = storedValue;
        setInputValue(storedValue);
      }
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <Autocomplete
        options={filteredAirports}
        value={selectedValue}
        onChange={(event, newValue) => {
          setSelectedValue(newValue);
        }}
        inputValue={inputValue}
        onInputChange={(event, newInputValue) => {
          setInputValue(newInputValue);
          handleInputChange(event, newInputValue);
        }}
        className="home__input"
        renderInput={(params) => (
          <TextField
            {...params}
            inputRef={inputRef}
            label="Try searching a gate in newark. Eg. 71x"
            margin="normal"
            InputProps={{
              ...params.InputProps,
              endAdornment: null,
              onBlur: handleBlur,
              onFocus: handleFocus,
            }}
          />
        )}
        renderOption={(props, option, { inputValue }) => {
          const matches = match(option.name, inputValue, { insideWords: true });
          const parts = parse(option.name, matches);
          return (
            <li {...props}>
              <div>
                {parts.map((part, index) => (
                  <span
                    key={index}
                    style={{
                      fontWeight: part.highlight ? 700 : 400,
                    }}
                  >
                    {part.text}
                  </span>
                ))}
              </div>
            </li>
          );
        }}
        noOptionsText="Where are you flying to?"
        filterOptions={(x) => x}
        disableClearable
        forcePopupIcon={false}
      />
      <button className="home__search" type="submit">
        Search
      </button>
    </form>
  );
};

export default Input;

this is the code and you can access the public ip on – https://18.224.64.51

For example i entered/typed New York in the searchbar and then when i click on any blank space of the same page or click the tab button the entered text disappears from the searchbar

how do i make sure that no matter where i click on the browser or click any button the entered text stays the same?

TypeError: Cannot read properties of undefined (reading ‘quantity’)

Ecommerce site using MERN. This is the Navbar.jsx component. Error shows cant read undefined ‘quantity’ on line 72.
ERROR MESSAGE
Uncaught TypeError: Cannot read properties of undefined (reading ‘quantity’)

import { Badge } from "@material-ui/core";
import { Search, ShoppingCartOutlined } from "@material-ui/icons";
import React from "react";
import styled from "styled-components";
import { mobile } from "../responsive";
import { useSelector } from "react-redux";
import { Link } from "react-router-dom";



const Navbar = () => {
  const quantity = useSelector(state=>state.cart.quantity)
  return (
    <Container>
      <Wrapper>
        <Left>
          <Language>EN</Language>
          <SearchContainer>
            <Input placeholder="Search" />
            <Search style={{ color: "gray", fontSize: 16 }} />
          </SearchContainer>
        </Left>
        <Center>
          <Logo>LAMA.</Logo>
        </Center>
        <Right>
          <MenuItem>REGISTER</MenuItem>
          <MenuItem>SIGN IN</MenuItem>
          <Link to="/cart">
          <MenuItem>
            <Badge badgeContent={quantity} color="primary">
              <ShoppingCartOutlined />
            </Badge>
          </MenuItem>
          </Link>
        </Right>
      </Wrapper>
    </Container>
  );
};

export default Navbar;
ERROR MESSAGE
Uncaught TypeError: Cannot read properties of undefined (reading 'quantity')
    at Navbar.jsx:72:1
    at useSelector.ts:182:1
    at memoizedSelector (use-sync-external-store-with-selector.development.js:78:1)
    at getSnapshotWithSelector (use-sync-external-store-with-selector.development.js:133:1)
    at mountSyncExternalStore (react-dom.development.js:16799:1)
    at Object.useSyncExternalStore (react-dom.development.js:17727:1)
    at useSyncExternalStore (react.development.js:1676:1)
    at useSyncExternalStoreWithSelector (use-sync-external-store-with-selector.development.js:144:1)
    at useSelector2 (useSelector.ts:249:1)
    at Navbar (Navbar.jsx:72:1)

How to solve this issue

I could not understand why it is showing undefined

EDIT:

Here are the redux files where i defined the schema:

file1 :cartRedux.js

import { createSlice } from "@reduxjs/toolkit";

const cartSlice = createSlice({
  name: "cart",
  initialState: {
    products: [],
    quantity: 0,
    total: 0,
  },
  reducers: {
    addProduct: (state, action) => {
      state.quantity += 1;
      state.products.push(action.payload);
      state.total += action.payload.price * action.payload.quantity;
    },
  },
});

export const { addProduct } = cartSlice.actions;
export default cartSlice.reducer;

File 2: store.js

import { configureStore, combineReducers } from "@reduxjs/toolkit";
import cartReducer from "./cartRedux.js";
import userReducer from "./userRedux.js";
import {
  persistStore,
  persistReducer,
  FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER,
} from "redux-persist";
import storageSession from 'redux-persist/es/storage/session.js'

const persistConfig = {
  key: "root",
  version: 1,
  storage:  storageSession,
};

const rootReducer = combineReducers({ user: userReducer, cart: cartReducer });

const persistedReducer = persistReducer(persistConfig, rootReducer);

export const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
    }),
});

let persistor = persistStore(store);
export default persistor;

Getting the Editor Content based on the Cursor Position in a Vs Code Extension

1Are there some available ways for getting the entire function based on the current cursor position in the Vs code Editor ,
For Eg. Refer This Image here my cursor is at a line inside the function , based on this is there a way we can take that entire function ?
We use vscode.window.activeTextEditor.selection to get the current selection, is there a way i can get the entire function based on the cursor position?

There is a way where we can pass the entire open file content , but i want to know is there a way we can get the function based on the cursor position.

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax,

This is the error i am getting:

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

By default "node_modules" folder is ignored by transformers.

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
 • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:   
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation

^^^^^^^

    SyntaxError: Cannot use import statement outside a module

    > 1 | import axios from "axios";
        | ^
      2 |
      3 | export const GETAPI = (endpoint, params, apiUrl = "", dump = false) => {

Here is my jest.config.js file

module.exports = {
  collectCoverage: true,
  collectCoverageFrom: ["src/**/*.{js,jsx}"],
  coverageDirectory: "coverage",
  testEnvironment: "jsdom",
  setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
  transformIgnorePatterns: [
    '<rootDir>/node_modules/',
  ],
  transform: {
    "^.+\.(js|jsx|ts|tsx)$": "ts-jest",
  },
  moduleNameMapper: {
    "\.(css|less|scss|sass)$": "<rootDir>/__mocks__/styleMock.js",
    "\.(jpg|jpeg|png|gif|webp|svg)$": "<rootDir>/__mocks__/fileMock.js"
  }
};

Here is my jest.setup.js

import '@testing-library/jest-dom'

And this is in my package.json

"scripts":{
     "test": "react-scripts test --detectOpenHandles",
    "coverage": "jest --coverage"
},
"babel": {
    "presets": [
      "@babel/preset-env",
      "@babel/preset-react"
    ],
    "plugins": [
      "@babel/plugin-syntax-jsx"
    ]
  },
"devDependencies": {
    "@babel/plugin-syntax-jsx": "^7.24.7",
    "@babel/preset-react": "^7.24.7",
    "@testing-library/jest-dom": "^6.4.8",
    "@testing-library/react": "^16.0.0",
    "jest": "^29.7.0",
    "jest-environment-jsdom": "^29.7.0",
    "path": "^0.12.7"
  }, 

Can Anyone please point out what is wrong here ? Thanks a lot.

Javascript: Any way to create a class by constructing class name using strings/variables dynamically without eval?

I’ve tried myriads of ways to create new class instances dynamically, without using eval and hard coded key-value pairs, to no avail. Seemingly there is no way in modern Javascript to query the user defined classes and/or to create them. Is there any remedy to my problem?

Example:

class Whatever {}
class Anything {}
classes = {Whatever, Anything}

//These ofc doesn't work 
instance = new ['Whatever']()
instance = new window['Whatever']()

//This works, but eval...
x = eval('Whatever')
instance = new x()

//This also works, but with mapping, not nice

new window['classes']['Whatever']()

Fix for AMP Error caused by the Imply script tag in nextjs App

Tag found outside the document head which is only allowed as a direct child of the document head.

Error:
Invalid attribute: data-amp-bind

Fix:
Ensure that you are using only allowed attributes for AMP components. If you’re using custom attributes, they should be part of the AMP component’s documentation.

JavaScript Errors
Error:
Custom JavaScript not allowed

enter image description here

export const AmpImplyTracking = () => {
const url = 'ua.google.com';
const encodedUrlUA = encodeURIComponent(url);

    return (
        <script id="amp-access" type="application/json" 
            dangerouslySetInnerHTML={
                { __html: `
                    {
                        "authorization" : "https://${encodedUrlUA}/api/resolve/genfpamp?channel=2&source=5&fpid=READER_ID&requrl=SOURCE_URL&reqref=DOCUMENT_REFERRER&host=indianexpress.com",
                        "noPingback": true,
                        "authorizationFallbackResponse": {
                                "error": true
                        },
                        "namespace": "usercapturing"
                    }
                `}
            }
        />
    )
}

still giving error after using the use client on top in next.js component

× You’re importing a component that needs useRouter. It only works in a Client Component but none of its parents are marked with “use client”, so they’re Server Components by default.error message

"use client ";
import { useRouter } from 'next/navigation'


export const NavBar = () => {
const router = useRouter()

return (
    <div className='fixed inset-x-0 top-0 h-20 bg-gray-900 flex items-center justify-between px-10'>
        <div>

        </div>
        <div>
            <button
                onClick={() => router.push('/api/auth/signin')}
                className='bg-blue-500 text-white px-4 py-2 rounded-md'>
                Login
            </button>
        </div>
    </div>
)}

as you can see i using the ‘use client’ on top of file but still its giving me error, that i can not use useRouter in client component and its showing mark the parent component as ‘use client’, then my whole page will become client component if i mark it.

then what the point to use the next.js if my whole page is client component. help me to solve it without making parent component as client component.

How to convert this raw pdf to pdf file

I have an api call which returns raw pdf. I’m storing them in a variable called rawpdf. I want to display that in my webpage. As shown her is the raw pdf file

//axios function retrned data
%PDF-1.4
%����
1 0 obj
<</Pages 2 0 R
/Metadata 3 0 R
/Type /Catalog
>>
endobj
2 0 obj
<</Kids [4 0 R]
/Count 1
/Type /Pages
>>
--------------encrypted content----------------------
<</Encrypt 10 0 R
/Info 11 0 R
/Root 1 0 R
/Size 12
/ID [<aead908ec8b33cff86b6a8aee8e4f48c><aead908ec8b33cff86b6a8aee8e4f48c>]
>>
startxref
5727
%%EOF

Not to complicate the data leak I had set encrypted message. I want to convert this message and show in a web Page.

I try to convert that by creating a blob and saved. but it’s not working.To be precise The i had reated showing empty.

const PdfViewer = () => {
  const [pdfUrl, setPdfUrl] = useState('');

  useEffect(() => {
    const fetchPdf = async () => {
      try {
        // Fetch the PDF data
        const response = await axioscalledhere();

        const data = response.data;
        
        const base64String = data.replace(/^data:application/pdf;base64,/, '');

        const binaryString = atob(base64String);

        const len = binaryString.length;

        const bytes = new Uint8Array(len);
        for (let i = 0; i < len; i++) {
          bytes[i] = binaryString.charCodeAt(i);
        }
        const blob = new Blob([bytes], { type: 'application/pdf' });
        const url = URL.createObjectURL(blob);
        setPdfUrl(url);

      } catch (error) {
        console.error('MAY DAY....MAY DAY... ERROR!:', error);
      }
    };

    fetchPdf();
  }, []);

  return (
    <div>
      {pdfUrl && (
        <iframe src={pdfUrl} style={{ width: '100%', height: '600px' }} title="PDF Viewer" />
      )}
    </div>
  );
};


export default PdfViewer;

JS promises will run parallelly or one by one

Need to now about the promises , The JS promises will run parallelly or not

this is the below code I’m using, Here I am creating three promises and checking the execution time

const startTime=Date.now()

const record1= new Promise((resolve,reject)=>{
  for(i=0;i<100;i++){
      for(j=0;j<100;j++){
          console.log(`${i}${j}`)
      }
  }
  resolve(Date.now()-startTime)
})

const record2= new Promise((resolve,reject)=>{
  for(k=0;k<100;k++){
      for(l=0;l<100;l++){
          console.log(`${k}${l}`)
      }
  }
  resolve(Date.now()-startTime)
})

const record3= new Promise((resolve,reject)=>{
  for(m=0;m<100;m++){
      for(n=0;n<100;n++){
          console.log(`${m}${n}`)
      }
  }
  resolve(Date.now()-startTime)
})
Promise.all([
  record1,
  record2,
  record3
]).then((msg)=>{
  console.log(msg)
})

This is the output I’m getting:

[ 1089, 2755, 3943 ]