why it only works if there is only line 14 in script ? if i dont comment out line 16 it does n’t work

i tried to replace the content in h2 tag id heading and h2 tag id last. i used two let in script. however, if i try to change both h2 it doesn’t work but if i comment out one it works.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h2 id="heading">fuck</h2>
    <h2 id="last">fuck</h2>
<script>
let change=document.getElementById('heading');
change.innerHTML="hello javascript from your mom";
// let last-second=document.getElementById('last');
</script>
</body>

</html>

Determine parent script of arbitrary function

Background

I have written a shim to make EventTarget.addEventListener agnostic to scripts that have the async tag set. The problem with this kind of scripts is that you absolutely cannot tell when loading it has completed so even though you may register handlers for the DOMContentLoaded and/or load events, they aren’t guaranteed to fire.

This inevitably means that every asynchronous script needs to bring a logic that allows it to determine at which stage during the load process it has started to execute, however, this inevitably means some bloat to these scripts (since each of them has to bring this logic along, that’s extraneous code that could be avoided).

This shim installs a wrapper function to the aforementioned addEventListener and also registers its own handlers for both DOMContentLoaded and load (the former of which is also used to collect a list of all scripts present when the DOM is completed). So if a script now registers handlers for either of the two events, it still receives the events even though they may already have fired.
Installing it allows developers to write asynchronous JavaScript like one that is executed synchronously or with the defer tag set and still receive these two events if desired and so avoids extraneous code in these scripts. It also makes it easy to switch between synchronous and asynchronous.

Inner Workings

To achieve this the shim checks whether any of the events has already fired. If not, the handler is enqueued normally via the native function so that the browser can handle dispatching the events where applicable. However, if the event in question has already fired, an artificial event is generated and the handler added directly to the microtask queue, which essentially causes its immediate invocation.

This is the code of the shim:

'use strict';

(function (window, document, undefined) {
const orig_add_ev_listener = Object.getOwnPropertyDescriptor(EventTarget.prototype, 'addEventListener').value;

var dom_avail = false;
var page_loaded = false;
var scriptlist = [ ];           // Scripts defined prior to the DOMContentLoaded event

// This makes addEventListener aware to the firing of both the DOMContentLoaded
// and the load event.
// If an event handler is supposed to be registered on any of these events,
// add them as microtasks in case the events have already been dispatched.
function exec_event(p_event, p_handler, p_param)
  {
var l_install_hand = true;
var l_custom_ev;

  if(typeof p_event != 'string')
    throw new TypeError('string expected');
  if(typeof p_handler != 'function')
    throw new TypeError('function expected');
  if(typeof p_param == 'undefined')
    p_param = { capture: false };
  if(typeof p_param == 'boolean')
    p_param = { capture: p_param };
  if(typeof p_param != 'object' || Array.isArray(p_param))
    throw new TypeError('boolean or non-array object expected');

  switch(p_event)
    {
    case 'DOMContentLoaded':
      if(this == document && dom_avail)
        {
        l_custom_ev = new Event('DOMContentLoaded');
        l_install_hand = false;
        }
      break;

    case 'load':
      if(this == window && page_loaded)
        {
        l_custom_ev = new Event('load');
        l_install_hand = false;
        }
      break;
    }
  if(l_install_hand)
    orig_add_ev_listener.call(this, p_event, p_handler, p_param);
  else
    queueMicrotask(p_handler.bind(this, l_custom_ev));
  }

document.addEventListener('DOMContentLoaded', p_event => {
var l_this;

  dom_avail = true;
  for(l_this of document.scripts)
    scriptlist.push(l_this);
  }, { once: true });
window.addEventListener('load', p_event => { page_loaded = true; }, { once: true });
Object.defineProperty(EventTarget.prototype, 'addEventListener', { value: exec_event });
})(window, document);

For synchronous or deferred scripts this is easy as they are going to get both events.
Asynchronous scripts, however, are treated a little differently, and depending on when the script is executed for the first time, the behavior of the wrapper differs:

  1. The document is still loading.
    The handlers are registered normally with the browser, and once they are due, they are invoked normally.
  2. DOMContentLoaded has already fired.
    If a handler is registered for this event, instead of registering it with the browser, an artificial event is created and the handler directly added to the microtask queue. This has the handler being invoked right after the current job completes. A handler for load is still registered normally.
  3. load has already fired.
    An artificial event is created in either case and the respective handler added to the microtask queue.

The Problem

Normally a script that registers handlers for these events after they have fired doesn’t get them invoked any more so this shim is working around that. However, in its current form it cannot distinguish between scripts that have been defined while the document was still loading and those that have been injected later on so the latter still would have any handlers for DOMContentLoaded or load executed. To emulate the usual behavior for these latecomers I need to find out which script element they are residing in.

Is there a means available for native JavaScript to figure out the parent element of a particular function, something that I could vet against scriptlist?
Please note that the wrapper for addEventListener can be executed at arbitrary times so document.currentScript is not an option. Also, the function that needs to be checked is passed as an argument to the wrapper so it isn’t running so anything that relies on that isn’t available, either. Please also avoid constructs like caller, callee, etc. as they aren’t an option in strict mode.

Is there way to access the URL the button will redirect to ifs decided by site JS code

I’m trying to scrape a website for product detail. So it has many buttons, for instance of below code.

<button aria-label="ARIA_LABEL_NAME" class="CLASS_NAME"><span class="CLASS_NAME"><img src="SRC_REMOVED" alt="" class="e-1yuw6bt"></span></button>

Now when I click above button on the site, it dynamically loads the product details and the source site(from where I original clicked the button) state is lost.
There are some other buttons of other products too but those when clicked just change the URL of the source site and then opens a popup without dynamically loading the new site (by replacing its complete HTML content with source site).

Now the thing is that for me the URL is of usefulness as it contains SKU which I can not find elsewhere.

I tried many solutions but none works for instance preventing propagation of that button event(result: clicking any button or this button will do nothing).

The above implementation is part of Chrome Extension Manifest V3.

What I am looking for
I would like to know if there is way to access what the button will redirect to without loading the content or somehow see the source code (which I tried but seems like its minified) that how this button JS code works so I can have some clue or some other solution.
Thanks!

How can I save the photo that the user has changed?

I have a picture that I divided into different areas, when the user clicks on each area, a cross appears on that area. I did this with html and javascript.
Now I want this photo to be saved with its changes when the save button is clicked.
My environment is Oracle Apex.
How can I do this?

Pressing consent button with puppeteer

I am using "puppeteer": "^19.11.1",:

I created this function to press the consent button on this Page:

enter image description here

This is my function:

async function handleConsent(page, logger) {
    const consentButtonSelector =
        '#uc-center-container > div.sc-eBMEME.ixkACg > div > div > div > button.sc-dcJsrY.bSKKNx';


    try {
        // Wait for the iframe to load
        await page.waitForSelector("iframe", { timeout: 3000 });

        // Identify the iframe that contains the consent button
        const iframeElement = await page.$(
            'iframe[name="__tcfapiLocator"]'
        );
        if (iframeElement) {
            const iframeContent = await iframeElement.contentFrame();

            // Attempt to click the consent button within the iframe
            const consentButton = await iframeContent.$(consentButtonSelector);
            if (consentButton) {
                await iframeContent.click(consentButtonSelector);
                logger.info("Consent button clicked inside the iframe.");
            } else {
                logger.info("Consent button not found inside the iframe.");
            }
        } else {
            logger.info("Iframe with the consent message not found.");
        }

        await page.waitForTimeout(3000); // Wait for any potential redirects or updates after clicking
    } catch (error) {
        logger.error(`An error occurred while handling consent: ${error}`);
    }
}

My problem is that the selector is not found, even though I am trying to select the iframe.

Any suggestion on what I am doing wrong?

I appreciate your replies!

Limit range from start to end in Joi validation

Add Joi validation in nodeJs to limit endDate to be no more than 3 years after startDate.

Example :
startDate 2024-03-29 ,
max endDate should be: 2027-03-29.

I tried:

const maxEndDate = Joi.ref('startDate', {
  adjust: startDate => startDate.getTime() + 1000 * 60 * 60 * 24 * (365 * 3)
});

const validate =
  query: {
    endDate: Joi.date().format(DATE_FORMAT).utc().min(Joi.ref('startDate')).max(maxEndDate).raw().required(),
  }

and

const maxEndDate = Joi.ref('startDate', { adjust: ['+3 years'] })

but looks like it doesn’t add 3 years, it only takes startDate as ref and gives error:

"message": ""endDate" must be less than or equal to "Fri Mar 29 2024 03:00:00 GMT+0300"

lerna “Assuming all packages changed” for new branches

I have a monorepo with Lerna configured version to independent
the problem is whenever create i a new git branch and run version or publish I get Assuming all packages changed and lerna wants to bump all packages although I didn’t do any change. if I go back to master lerna will know to continue from there.

I tried running it with –include-merged-tags but it didn’t help as well

if I do publish from-package then it works well but that means I need to handle the version manually, something I want to avoid

Svelte Component Errors: Cannot read properties of null (reading ‘current’), TypeError: unsubscribe is not a function

I have a component that accesses a svelte store writable but the component just gets rendered before the data arrives into the store variable.

This are the errors
enter image description here

I want this component to start rendering when there is some data in currentOneCallData.

<script>
  import { onDestroy, onMount } from "svelte";
  import rain from "../assets/icons/d-rain.png";
  import { currentOneCallData } from "../cli";

  let unsubscribe;
  let loading = true;

  onMount(() => {
    unsubscribe = currentOneCallData.subscribe(value => {
      if(value !== undefined){
        loading = false;
        unsubscribe();
      }
    })
  })

  onDestroy(() => {
    if(unsubscribe) {
      unsubscribe(); 
    }
  });

  function convertUnixTimestamp(timestamp) {
    const months = [
      "Jan",
      "Feb",
      "Mar",
      "Apr",
      "May",
      "Jun",
      "Jul",
      "Aug",
      "Sep",
      "Oct",
      "Nov",
      "Dec",
    ];
    const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

    // Convert timestamp to milliseconds
    const date = new Date(timestamp * 1000);

    // Extract day, month, and date
    const day = days[date.getDay()];
    const month = months[date.getMonth()];
    const dayOfMonth = date.getDate();

    // Concatenate and return formatted date
    return `${day}, ${month} ${dayOfMonth}`;
  }
</script>

I have also implemented conditional logic that prevents it from accessing data from object before its available.

{#if !loading}
  <div class="current-container">
    <div class="text-content">
      <div class="dateAndTime">
        <p class="date">{convertUnixTimestamp($currentOneCallData.current.dt)}</p>
        <p class="time">7:40 AM</p>
      </div>
      <p class="temp">{$currentOneCallData.current.temp}<sup class="temp-unit">°C</sup></p>
      <h4 class="feel-container">
        Feels like <span class="feel"
          >{$currentOneCallData.current.feels_like} <span class="temp-unit">°C</span></span
        >
      </h4>
      <h3 class="desc">{$currentOneCallData.current.weather[0].description}</h3>
    </div>
    <div class="icon-container">
      <img src={rain} alt="" class="icon" />
    </div>
  </div>
{:else}
  <div class="loading"><p>Loading...</p></div>
{/if}

jet smart filter auto page reload not work

SmartFilters have 3 option to filtter the data
AJAX
Page reload
Mixed
I want to use page reload, but currently, when using the page reload, I have to click on the “Apply Filter” button. Then, the page reloads and shows the result. However, what I want is for the page to reload automatically when I select any filter value.

document.addEventListener(‘DOMContentLoaded’, function() {
// Select your filter form or individual inputs
var filters = document.querySelectorAll(‘.jet-smart-filters select, .jet-smart-filters input[type=”checkbox”], .jet-smart-filters input[type=”radio”]’);

// Add change event listener to each filter
filters.forEach(function(filter) {
    filter.addEventListener('change', function() {
        // Adjusted to match the specific class of your apply button
        document.querySelector('.apply-filters__button').click();
    });
});

});

Make react-query useMutation to handle an Error

There’s a strange issue which I don’t undrestand – react-query’s useMutation doesn’t handle an error while @tanstack/react-query’s does.

A Sandbox

import { useState } from "react";
import {
  useQuery,
  useMutation,
  useQueryClient,
  QueryClient,
  QueryClientProvider,
} from 'react-query'
// import {
//   useQuery,
//   useMutation,
//   useQueryClient,
//   QueryClient,
//   QueryClientProvider,
// } from '@tanstack/react-query'

import axios from 'axios';

const postTodo = () => axios('https://ya.ru')

const ToDos = () => {
  const { mutate,isError } = useMutation({
    mutationFn: postTodo,
    onSuccess: () => {
      // Invalidate and refetch
      return true
    },
    onError: () => {
      throw new Error('this!')
    }
  })

  console.log(isError)

  return (
    <>
    <button onClick={mutate}>Mutate me!</button>
    {isError ? 'Error' : 'No Error'}
    </>
  )
}

// Create a client
const queryClient = new QueryClient()

export default function App() {

  return (
    <QueryClientProvider client={queryClient}>
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <ToDos />
    </div>
    </QueryClientProvider>
  );
}

In short what I want is to see an ‘Error’ when I press ‘Mutate me’, as it is when i use useMutation from @tanstack/react-query, but useMutation from react-query just throws an error and the execution breaks. I have to use react-query, not @tannstack/react-query on my project.

I tried throwOnError, but it doesn’t work there

Code gets Stuck in Bull.Js process function and never terminated

code never reaches console.log(“All job completed”) and gets stuck in process function it is still waiting for job to processed even though there are no jobs present in queue how to resolve this

import Bull from 'bull';

const queue = new Bull('my-queue');

await queue.add({ data: 'Job 1' });

await queue.process(10,async(job,done)=>{
    try{
    console.log('Processing Job:', job.data);
    await new Promise(resolve => setTimeout(resolve, 1000));
    done(null,job.data);
    }catch(err){
        done(err);
    }
})
console.log("All job completed ");

I want that if there are no jobs in queue then queue instance should be deleted and process function should be resolved

Trying to make a loop where the remainder is 25

I am trying to do a loop that have to print x,y values until the remainder of the operation is 25 and the loop stop.

However, my first iteration of the code get Uncaught ReferenceError: Cannot access ‘x’ before initialization . Therefore, I decide to change it and use For, but does not mater if I use z<25 or z<=25 the loop wont stop.

//first iteration
let x=20;
let y=15;
let z=0;
while(z<=25){
let x=x+25;
let y=y+15;
let z=x%y;
console.log(x,y);
}
    //second iteration
for( let z=0;z<25; x++,y++) {
let z=x%y;
console.log(x,y);

SharedWorker close Memory leaks due to invalidity

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="root"></div>
    <button id="btn">click</button>
  </body>

  <script>
    const btn = document.getElementById("btn");

    function a1() {
      let shared = new SharedWorker("./1.js");

      if (shared !== null) {
        shared.port.close();
        shared = null;
      }
    }

    btn.onclick = () => {
      for (let i = 0; i < 20 * 1000; i++) {
        setTimeout(a1, 0);
      }
    };
  </script>
</html>

// 1.js
onconnect = (ev) => {
  ev.ports[0].close();
};

I shut it down, but it still doesn’t free up memory.
I checked it with chrome memory and it showed no release, but I didn’t have any references to it.

enter image description here

Normal memory release

Directly manipulating size of “windows” in P5.js

Trying to manage resizing a window (rect) in a p5.js sketch to achieve a similar result to what I’ve demonstrated here. The full p5.js project is available here. Hope someone can help, bearing in mind I’m not a dev by any means but trying to learn. Thanks in advance.

contains(x, y) {
        return x > this.x - this.w/2 && x < this.x + this.w/2 &&
               y > this.y - this.h/2 && y < this.y + this.h/2;
    }

    resize(mouseX, mouseY) {
    const margin = this.w * this.resizeThreshold;

    if (dist(mouseX, mouseY, this.x + this.w / 2, this.y + this.h / 2) < margin) {
      this.resizeOriginX = mouseX;
      this.resizeOriginY = mouseY;
      this.isResizing = true;
    } else {
      this.isResizing = false;
    }
  }
}

let windows = [];
let selectedWindow = null;

// Event handlers

function mousePressed() { 
    for (let i = windows.length - 1; i >= 0; i--) {
        windows[i].resize(mouseX, mouseY); 
        if (windows[i].contains(mouseX, mouseY)) {
            selectedWindow = windows[i];
            windows.splice(windows.indexOf(selectedWindow), 1); 
            windows.push(selectedWindow); 
            return;
        }
    }
    selectedWindow = null; 
}

function mouseDragged() {
  if (selectedWindow) {
    if (!selectedWindow.isResizing) { 
      selectedWindow.x = mouseX;
      selectedWindow.y = mouseY;
    } else {

      const newWidth = mouseX - selectedWindow.resizeOriginX;
      const newHeight = mouseY - selectedWindow.resizeOriginY;
      print(`newWidth = ${mouseX} + ${selectedWindow.resizeOriginX}`);
      print(`newWidth = ${mouseY} + ${selectedWindow.resizeOriginY}`);

      selectedWindow.w = newWidth;
      selectedWindow.h = newHeight;
    }
  }
}

function mouseReleased() {
    if (selectedWindow) {
        selectedWindow.isResizing = false;
        selectedWindow = null; 
    }
}

Pwa standalone ios safari audio record

Does anyone have an idea on how to record audio in iOS iPhone PWA standalone mode? I’m facing an issue where my PWA works well on Safari, but when I add it to the home screen in standalone mode, it asks for permission to access audio. I grant permission, but the audio is not recorded; it just produces a beep sound. Does anyone know how to fix this?

Thanks,
Usama