How to override constructor of prototype/intercept object creation in JavaScript?

I would like to intercept all instance creations of EventSource. I tried the following code:

EventSource.prototype.constructor = function(url, config) {
    EventSource(url, config);
    console.log("intercepted");
}

to override the constructor. It does not work. But the following does work:

EventSource.prototype.sayHi = () => alert("Hi");
new EventSource("my-data").sayHi()

How can I achieve something similar for the constructor/in general instance creation?

I tried searching on the internet and the above code.

Why doe TextLayerBuilder in pdf.js not properly scale selectable text?

I am using pdf.js in a custom viewer window to display PDF’s and I’m trying to implement a way to make the text selectable. Apparently he only good way to do this is with the textLayerBuilder. My problem is that it is doing a terrible job at lining up the highlightable text over the real text and everything I find online I can either confirm is not my problem, or is no longer an option (setTextLayer)
Here are two pictures that show my current issue[Left: selected text in textLayer, Right: CSS adjusted to show textLayer text][1]
[1]: https://i.sstatic.net/TMZjmxRJ.png

Why does it do just a bad job with the fontSize and the scaleX properties? For the header, it actually was set to a much larger font size, but then was scaled down through other methods for some reason. I could show some code, but my code is a mess right now as I have been commenting out old sections of code to replace parts with bits I find online, and it’s a mess right now.

How to prevent Chrome from downloading a file when intercepted via a content script in Manifest V3?

I’m building a Chrome extension (Manifest V3) that intercepts file download links (e.g., .zip, .exe, .mp4, etc.) on pages like thank-you or success pages, and redirects them to my desktop app (Fetchify) instead of letting Chrome download them directly.

I’m successfully sending the download URL to my app, but Chrome still starts downloading the file, even though I’m calling e.preventDefault() and e.stopPropagation() in my content script.

My goal:

Intercept download links and:

1. Prevent Chrome’s native download

2. Send the file URL to my local app via HTTP POST

What’s working:

-> The content script detects download links.

-> The download URL is sent to my local app (http://localhost:12345/api/download).

What’s not working:

-> Chrome still downloads the file natively, even after interception.

My manifest.json :

{
  "manifest_version": 3,
  "name": "Fetchify Downloader",
  "version": "1.0",
  "description": "Send downloads directly to the Fetchify app from your browser.",
  "background": {
    "service_worker": "background.js"
  },
  "permissions": [
    "downloads",
    "contextMenus",
    "activeTab",
    "scripting"
  ],
  "content_scripts": [
  {
    "matches": ["<all_urls>"],
    "js": ["autoDownloadScript.js"],
    "run_at": "document_idle"
  }
],
  "host_permissions": ["<all_urls>"],
  "icons": {
    "16": "icons/icon16.png",
    "32": "icons/icon32.png",
    "48": "icons/icon48.png",
    "128": "icons/icon128.png"
  }
}

My autoDownloadScript.js :

(function () {
  const downloadExtensions = /.(zip|exe|mp4|mp3|pdf|iso|rar|7z|msi|deb|apk|tar.gz|docx?|xlsx?|pptx?)$/i;

  function sendToFetchify(url) {
    console.log("[Fetchify] Auto-detected download:", url);

    fetch("http://localhost:12345/api/download", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ url })
    })
      .then(res => {
        if (res.ok) console.log("✅ Sent to Fetchify.");
        else console.warn("⚠️ Rejected by Fetchify.");
      })
      .catch(err => console.error("❌ Fetchify error:", err));
  }

  function interceptLinkClick(e) {
    const anchor = e.target.closest("a");
    if (!anchor || !anchor.href) return;

    const url = anchor.href;

    if (downloadExtensions.test(url)) {
      e.preventDefault(); // Stop Chrome default download
      e.stopPropagation();

      console.log("[Fetchify] Intercepted link click:", url);
      sendToFetchify(url);
    }
  }

  function preventDefaultOnMatchingLinks() {
    const links = document.querySelectorAll("a[href]");
    for (const link of links) {
      if (downloadExtensions.test(link.href)) {
        link.addEventListener("click", e => {
          e.preventDefault();
          e.stopPropagation();
          sendToFetchify(link.href);
        });
      }
    }
  }

  function tryAutoDetectDownloadLinks() {
    const links = Array.from(document.querySelectorAll("a[href]"));
    for (const a of links) {
      if (downloadExtensions.test(a.href)) {
        console.log("[Fetchify] Auto-detected static link:", a.href);
        sendToFetchify(a.href);
        break; // Only handle one
      }
    }
  }

  // Intercept user clicks early (for dynamic DOM)
  document.addEventListener("click", interceptLinkClick, true);

  // Prevent static links from triggering download
  window.addEventListener("DOMContentLoaded", preventDefaultOnMatchingLinks);

  // Auto-detect on thank-you/success pages
  window.addEventListener("load", () => {
    const url = window.location.href.toLowerCase();
    if (url.includes("thank-you") || url.includes("success")) {
      setTimeout(tryAutoDetectDownloadLinks, 1500);
    }
  });
})();

What I’ve tried:

-> Using e.preventDefault() and e.stopPropagation() in both capturing and bubbling phases.

-> Adding both DOMContentLoaded and click interception.

-> Matching <all_urls> and running on document_idle.

Questions:

1. Is there a reliable way to prevent the browser from downloading the file when the link is clicked?

2. Should I be handling this at a different level (e.g., background script or with chrome.webRequest)?

3. Is there a way around this in Manifest V3 or any known workaround?

SyntaxError: Cannot create a key using the specified key usages

In my real task, I pass a private key from one Web page to another in URL string (yes, I know that this is not secure).

Here is a simplified code that prints in browser console an error that I don’t understand:

SyntaxError: Cannot create a key using the specified key usages.
<html>
    <head>
        <script>
async function main() {
    const pair = await window.crypto.subtle.generateKey(
        {name: 'ECDSA', namedCurve: 'P-256'/*secp256k1*/}, true, ['sign', 'verify']
    );

    const frontendTweakPrivKey = await window.crypto.subtle.exportKey("pkcs8", pair.privateKey);

    const privKeyUsable = await window.crypto.subtle.importKey(
        "pkcs8", frontendTweakPrivKey, {name: 'ECDSA', namedCurve: 'P-256'/*secp256k1*/}, false, ["sign", "verify"]
    );
}
(async () => main())();
        </script>
    </head>
</html>

(In my real code) the key is generated on the first Web page, encoded base64, and then decoded on another Web page it signs a message.

What does the error mean and how to fix it?

Remark: The key is generated on the first page and passed to the second one in order to “confirm” that the first page and the second page were browsed by the same user, not a hacker that simulates the user on the second page.

Using Tlvs in smpp in nestjs

I need help in sms integration using smpp in nestjs/Nodejs as we all know smpp takes only 4 mandatory values like this :

 session.submit_sm(
        {
          destination_addr: to,
          source_addr: senderId,
          short_message: text,
          data_coding: 0,
         }
  )

but also i want to use tlvs here so that required data send to sms gateway so yet we have two ways one is in older version and second is in newer version :
older one

session.submit_sm(
            {
              destination_addr: to,
              source_addr: senderId,
              short_message: text,
              data_coding: 0, 
              optionalParameters: [
                {
                  tag: 0x1502, 
                  length: templateId.length,
                  value: templateId,
                },
                {
                  tag: 0x1503, 
                  length: entityId.length,
                  value: entityId,
                },
              ],
            },

and newer one is like this :

session.submit_sm(
            {
              destination_addr: to,
              source_addr: senderId,
              short_message: text,
              data_coding: 0, 
              0x1503: Buffer.from(entityId), 
              0x1502: Buffer.from(templateId), 
            },

But both are not working as i check pcap in which check submit_sm data in which tlv data are not going so help me regarding this as soon as possible guys.

Tell any way so that i can send tlv ?

Puppeteer “TimeoutError is not defined”

I have a very simple web scraper app whose sole purpose is to evaluate the javascript on a webpage and return the generated HTML. It works fine most of the time. However, it is not handling timeouts in the way I need it to.

The code is called by an applescript handler which passes in a timeout value and needs to be specifically signalled when the timeout has elapsed.

I adapted some code from here, and although I don’t have much experience (at all) with javascript itself I believe I can see what it’s doing. Trouble is, at runtime I’m being told that TimeoutError doesn’t exist. I assume it’s defined somewhere in the puppeteer infrastructure, and I require puppeteer (puppeteer stealth, actually, but the problem occurs with straight puppeteer also), so what the heck?

I have an SSCCE which should demonstrate it:

//**************************************** constants

// all error codes that we pass back
const ERROR_CODE_URL_INVALID = 1002;
const ERROR_INTERNAL_SERVER_ERROR = 1003;
const ERROR_TIMEOUT = 1004;


//**************************************** scrape
const scrape = async (page, url) => {
    let response = null;

    // load the URL and check it's something useful
    let errorContent = null;
    try {
        // deliberately tiny timeout value, to demonstrate problem
        response = await page.goto(url, { waitUntil: 'load', timeout: 100 });
        if (!response) {
            // sometimes the response is not returned immediately, so we need to wait for it
            response = await page.waitForResponse(() => true, { timeout: 100 });
        }

        if (response.status() === 200) {
            // success; nothing to do here
        }
        else if (response.status() === 404) {
            // get ready to throw a 404 below
            errorContent = ERROR_CODE_URL_INVALID;
        } else if (response.status() === 500) {
            // get ready to throw a 500 below
            errorContent = ERROR_INTERNAL_SERVER_ERROR;
        } else {
            // throw whatever else we have down to the catch block
            throw response.text;
        }
    } catch (error) {
            if (error instanceof TimeoutError) {
                // get ready to throw a timeout to our caller
                errorContent = ERROR_TIMEOUT;
            }
            else {
                // rethrow the error we got above
                throw error;
            }
    }
    // now throw whatever error we got above
    if (errorContent !== null) {
        throw errorContent;
    }

    // get ready to scrape the page HTML
    // first hopefully get rid of any annoying popups in the way
    page.mouse.click(1, 1);

    // get the page HTML and return it
    const data = await page.evaluate(() => document.querySelector('*').outerHTML);
    return data;
} // scrape()

//**************************************** main
let browser;
(async function main() {
    // puppeteer-extra is a drop-in replacement for puppeteer,
    // it augments the installed puppeteer with plugin functionality
    const puppeteer = require('puppeteer-extra');
    // use the following line instead of the above one if not doing puppeteer stealth
    //const puppeteer = require('puppeteer');

    // add stealth plugin and use defaults (all evasion techniques)
    const stealthPlugin = require('puppeteer-extra-plugin-stealth')
    puppeteer.use(stealthPlugin())

    // start up the browser and get a page
    browser = await puppeteer.launch({headless: false});
    const [page] = await browser.pages();
    
    // get the page HTML and return it
    let s = await scrape(page, "https://www.scrapethissite.com/pages/");
    console.log(s);
})()        
.catch(err => console.log(err))
.finally(() => browser?.close());

I’d be grateful for help resolving this!

Can a promise resolve statement await a return from the function awaiting the promise?

In this example code, the showMenu button requests a sort of custom context menu which returns a promise waiting for the user to make a selection from the menu. When the menu is requested, a busyType is passed indicating whether or not other events should be blocked until the work of the menu selection is complete.

Once the user makes a selection, I’m trying to get function BusyHandler to wait for SelectionHandler to wait for OptionHandler (where the “real” async work is performed). However, BusyHandler is done waiting before OptionHandler completes; and I think it is because all SelectionHandler does is resolve the promise and, apparently, that is not something that can be awaited. I don’t want SelectionHanlder to return to the await of BusyHandler until the the setTimeout in OptionHandler completes.

Is this possible and, if so, can you show how to do it? Thank you.

When run the snippet, click the Show Menu button to display the menu, select either option from the menu which will then close, and the console log will show that BusyHandler is done waiting before the setTimeout of OptionHandler completes.

let 
   showMenu = document.querySelector(".showMenu"),
   menu = document.querySelector(".menu"),
   mapObj = Object.create(null)
;
mapObj.busyType = '';
mapObj.busyState = 0;
showMenu.addEventListener('mousedown', OptionHandler, false);
menu.addEventListener('mousedown',BusyHandler, false);
async function OptionHandler() {
  let option = await MenuHandler('b');
  console.log(option);
  let d = Date.now();
  console.log(`Work began at ${d}`);
  let p = new Promise( (resolve,reject) => {
     setTimeout( () => {resolve('delay resolved');}, 2000);
  });
  await p;
  console.log(`Work completed at ${Date.now()-d}`);
}
function MenuHandler(busyType) {
   menu.classList.add('show');
   mapObj.busyType = busyType;
   return new Promise( (resolve, reject) => {
     mapObj.resolve = resolve;
     mapObj.reject = reject;
   });
}
async function SelectionHandler(evt) {
  let e = evt.target;
  if (
        !e.matches('.menu button, .menu button *')
     || !(e = e.closest('button')) ) return;
  menu.classList.remove('show');
  await mapObj.resolve(e.value);

}
async function BusyHandler(evt) {
  if ( mapObj.busyType === 'b' ) {
    if ( mapObj.busyState === 1) return;
    mapObj.busyState = 1;
    await SelectionHandler(evt);
    console.log("BusyHandler done waiting");
    mapObj.busyState= 0;
  } else {
    SelectionHandler(evt);
  }
}
.menu {
  display: none;
  border: 1px solid black;
  padding: 10px;
  flex-flow: column;
  width: fit-content;
}
.menu.show {
  display: flex;
}
button {
  margin: 5px;
}
<button class="showMenu">Show Menu</button>
<div class="menu">
  <button value=1>Option 1</button>
  <button value=2>Option 2</button>
</div>

Why does destructuring assignment in JavaScript skip certain values in async iterators?

I’m trying to destructure values from an async generator in JavaScript, and I noticed that when I use a for await…of loop with array destructuring, some values seem to be skipped or ignored.
Example:

async function* generate() {
  yield [1, 2];
  yield [3];
  yield [4, 5];
}

(async () => {
  for await (const [a, b] of generate()) {
    console.log('a:', a, 'b:', b);
  }
})();

Output:

a: 1 b: 2
a: 3 b: undefined
a: 4 b: 5

I expected the second iteration to throw an error or something else. Why does JavaScript treat the second yield ([3]) like [3, undefined] instead of erroring out or skipping? Is it intentional or just a bug?

I’m also wondering how to avoid this when destructuring from generators with inconsistent returns.

How can I update an which I injected into a webpage with a Chrome Extension?

Title. I am trying to make a custom side panel using <iframe> instead of using Chrome’s sidePanel which cannot be programatically opened. However, when I try to edit the HTML of the <iframe> which I injected myself using javascript, I run into this error:
Uncaught SecurityError: Failed to read a named property 'document' from 'Window': Blocked a frame with origin "https://www.nytimes.com" from accessing a cross-origin frame.

This is my current approach in content.js:

const iframe = document.getElementById("wordle-panel");

iframe.addEventListener('load', function() {
    const panelDoc = iframe.contentWindow.document;
    
    const today = new Date().toISOString().slice(0, 10);
    todayStats = getUserStats()[today];
    if (todayStats) {
        const todayGuessesElement = panelDoc.getElementById("todayGuess");
        todayGuessesElement.textContent = `You completed Wordle today on your ${todayStats}th guess!`
    }
});

Angular method call in a template expression 4 times

here is my code:

import { Component } from ‘@angular/core’;

@Component({
  selector: 'app-root',
  standalone: true,
  template: `
    <h1>{{getTitle()}}</h1>
  `,
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'app-angu-tur';

  public getTitle():string  {
    console.log("log get title");
    return this.title;
  }
}

I created an angular project using ng new command, I also changed the code a little bit to test and I checked in devtool and saw that the console log function was printed 4 times. What I am wondering is why it is printing 4 times, I thought it would print maximum 2 times ? Thanks for reading

graph.facebook.com/v23.0/upload: trouble

I’m using Facebook API to upload a video to a page, this process takes three steps, I’m having trouble in step two. I’m using Postman to test, and it works well, but when i try to use javascript fetch it returns CORS erros:
Cross-origin request blocked: The Same Origin directive
the tutorial I’m following is this:
https://developers.facebook.com/docs/video-api/guides/publishing/

the code:
fetch(‘https://graph.facebook.com/v23.0/upload:MTphdHRhY2htZW50OmNkMTQ3YWYzLTM0OTYtNDVlMC05NWM5LTIxYmY2NDQzYTZlMT9maWxlX2xlbmd0aD03ODg0OTMmZmlsZV9uYW1lPU4wUzE4VUI0MVhhbE9GU2dNVnFQT0w5THJwMEhsRVg1T09CMUl1ZmoubXA0JmZpbGVfdHlwZT12aWRlbyUyRm1wNA==?sig=ARa1UcgneZD433_pBIc’, {
method: ‘POST’,
headers: {
‘Authorization’: ‘OAuth EAAKvuAnnoXcBO8UOPtAAdii0xZC5zKFy4TyMIVwJ6pJOmlZAuhlohwEHHvYL3lEUCAPIzdtlOKZA9IlTZBkvTmUzCfZC9nuVYHB8NAyOS3KmmgxaBgvkNdUIITVFQdlsIeZClL62FVBZCh6KkPZBlzaN4aF8u30YHsz0T2vuJYYCOVBq9wDfHhYKVdqhznBgRvxI’,
‘file_offset’: ‘0’,
‘Content-Type’: ‘video/mp4’,
“Origin”: “”
},
body: ‘@FILE_SRC’
});

How can i solve that?

How to click button from javascript extension with manifest v3?

I’m developing an extension for chrome and at some point it needs to click a button on the web page.
Up until now I used to just use the following code, but it doesn’t work anymore with manifest v3 (because CSP):

const button = document.getElementById("buttonId");
button?.click();

I’m looking for alternatives, but I can find very little info about this issue.
The only kinda working solution I found is to parse the href property of the button, extract explicit javascript the site executes on click and inject the script back to web page with a separate injector script described in the linked answer.

This method however feels like kind of overkill to simply click a button and I’d like to find a simpler solution. Do you have any ideas?

One thing I think might work is to pass the id to the service-worker and have it execute the script in world context that tries to find the given element and click it, but I’ll welcome other solutions.
I’m gonna update the question once I get some time to test it.

environment variables refuse to update

I was using a .env file to load in my environment variables in NextJs. one of which was a Cloudflare turnstile public key, I was using a testing key and wanted to use real one but it would not update the process.env variable for it. Its the same problem with all of the other variables in my .env

I have restarted the app,
deleted my .next folder,
deleted and resinstalled my node_modules,
restarted my computer,
searched through the filesystem to make sure i had not hard coded it anywhere,
and even deleted my .env file

it is a NEXT_PUBLIC_ variable and the problem is both server and clientside

I dont now what to do to fix it

EDIT:
Just to specify. my current .env/.env.local file looks like this

NEXT_PUBLIC_SUPABASE_URL='1234'
NEXT_PUBLIC_SUPABASE_ANON_KEY='1234'

# REAL KEY
NEXT_PUBLIC_TURNSTILE_SITE_KEY='0x1234'

# Always passes
# NEXT_PUBLIC_TURNSTILE_SITE_KEY='1x00000000000000000000AA'

but when i use something like

process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY

it returns
“‘1x00000000000000000000AA’ # Always passes”
which is what it used to be set to. But even if I delete the whole file, change the value, or anything, It ALWAYS prints out
“‘1x00000000000000000000AA’ # Always passes”.

Bar with title shows up on transparent overlay window

I currently want to write an overlay that uses Electron. The overlay is supposed to be transparent.
The window in question:

const mainWindow = new BrowserWindow({
    width: 100,
    height: 100,
    frame: false,
    alwaysOnTop: true,
    transparent: true,
    webPreferences: {
        nodeIntegration: true,
        contextIsolation: false,
    },
})

Issue

When I click within the window and then elsewhere, in another app or something outside the window, a top bar shows up. I tried this on two different machines, Windows 10 and 11. The main target is Windows users, so (eventually) Windows-only solutions are welcome.

I tried basically everything I could find, but it didn’t work, so I didn’t include all the researches in the window config here. According to tutorials I saw online, the way I’ve configured it, should work…

How it looks like

Image of window with some sort of bar/frame

Semi Working fixes

What kind of worked was setting frame: true and then setting the frame’s height to 0. However, this results in the window not being draggable.

The problem seems to be with the transparent: true, since when I remove it, the bar does not show up, but it is not transparent anymore (ofc) :’).

Reproduce/ Extra

main.ts

import { app, BrowserWindow } from 'electron'
import * as path from "node:path";

const createWindow = () => {
    const mainWindow = new BrowserWindow({
        width: 100,
        height: 100,
        frame: false,
        alwaysOnTop: true,
        transparent: true,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
        },
    })

    mainWindow.loadFile(path.join(__dirname, 'index.html'));
}

app.on('ready', () => {
    createWindow();
});

index.html

<!DOCTYPE html>
<html lang="en">
    <body>
    <h1>text</h1>
    </body>

</html>

Version

I tried Electron version 37.1.0 and 35.6.0


Thank you for any suggestions or help in advance!