How to import html2canvas in Chrome extension

I have created an extension to get a capture of the body with the following code, but I get an error message.

Please help.

[Error message]

Uncaught (in promise) TypeError: Failed to fetch dynamically imported module: chrome-extension://... /js/content.js

[Source code]
manifest.json

  "content_scripts": [
    {
        "matches": ["<all_urls>"],
        "js": [ "script.js" ]
    }
  ],
  "web_accessible_resources": [
    {
      "matches": ["<all_urls>"],
      "resources": [
          "js/content.js",
          "js/html2canvas.js"
      ]
    }
  ]

content.js

import html2canvas from './html2canvas';

let target_element = document.getElementsByTagName('body')[0];
let button_element = document.createElement('button');
button_element.setAttribute("id", "captcha-btn");
button_element.innerHTML = 'test';
target_element.prepend(button_element);

let target_pankuzu_element = document.getElementsByTagName('body')[0];
let img_element = document.createElement('img');
img_element.setAttribute("id", "result");
target_pankuzu_element.prepend(img_element);

const BUTTON_CLICK_EVENT= document.getElementById('captcha-btn');
BUTTON_CLICK_EVENT.addEventListener('click', () => {
    html2canvas(document.getElementsByTagName('body')[0],{}).then(function(canvas){
        document.getElementById('result').src = canvas.toDataURL();
    })
});

script.js

(async() => {
    const src = chrome.runtime.getURL("js/content.js");
    const contentMain = await import(src);
})();

To be executable without error.

Function return undefined

I have a function that return a undefined thing even if it normally need to return something defined.

I have this code with a function :

const GtfsRealtimeBindings = require("gtfs-realtime-bindings");
const fetch = require("node-fetch");
const long = require("long");

async function getTGVStops(tgv_number){

    var answer

    try {
      const response = await fetch("https://proxy.transport.data.gouv.fr/resource/sncf-tgv-gtfs-rt-trip-updates", {
        headers: {
          //"x-api-key": "<redacted>",
          // replace with your GTFS-realtime source's auth token
          // e.g. x-api-key is the header value used for NY's MTA GTFS APIs
        },
      });
      if (!response.ok) {
        const error = new Error(`${response.url}: ${response.status} ${response.statusText}`);
        error.response = response;
        throw error;
        process.exit(1);
      }
      const buffer = await response.arrayBuffer();
      const feed = GtfsRealtimeBindings.transit_realtime.FeedMessage.decode(
        new Uint8Array(buffer)
      );
      feed.entity.forEach((entity) => {
        if (entity.id.includes(tgv_number)) {
          answser = entity.tripUpdate.stopTimeUpdate
          console.log(answser)
          return answser
        }
      })
    }
    catch (error) {
      console.log(error);
      process.exit(1);
    }
}

module.exports = { getTGVStops }

and want to call it in an other files,

const tgv = require("./tgv_information.js")
const station = require("./station.js")
const GtfsRealtimeBindings = require("gtfs-realtime-bindings");

tgv.getTGVStops("6033").then((answer) => { 
    console.log("test")
    console.log(answer); 
});

But it always say undefined.

How to block iframe popup from external link

I’m using an iframe to embed an external videos. The problem is that when I click play button it is showing several times irrevelant popups pages with 18+ content until video start.

In order to block the popups I was using the iframe in sandbox mode like this:

<iframe sandbox="allow-same-origin allow-scripts" src="https://footballvid.com/yourvideo45"></iframe>

and it was working perfectly fine until today I get error message that embeded videos are not working anymore in iframe with sandbox tag and have to remove the sandbox.

Is there any other method similar with the sandbox tag to embed video and block annoying popups ?

I try to use iframe in sandbox mode but it’s not working anymore

Python CloudSCraper render JavaScript

As the title says, I am using CloudScraper to get CloudFlare secured website. I could get 200 response but the content is “You must enable javascript to view this page.” error message.
While trying to request the page through requests_html to render the JavaScript, I get 403 response with “CloudFlare | error cookies must be enabled” I already tried the different JavaScript interpreters in CloudScraper.
Is there a way to make the initial request using CloudScraper, and then pass it to requests_HTML to render the JavaScript?
Here is a sample of what I am trying to get

import cloudscraper
from bs4 import BeautifulSoup
from requests_html import HTMLSession

scraper = cloudscraper.create_scraper(browser={'browser': 'firefox','platform': 'windows','mobile': False})

html = scraper.get("https://visas-de.tlscontact.com/visa/eg/egCAI2de/home").content

session = HTMLSession()
#response = session.get(
     'https://visas-de.tlscontact.com/visa/eg/egCAI2de/home')
 rendered = response.html.arender(html)
 soup = BeautifulSoup(rendered.text, 'html.parser')

So basically the main idea is to get the page through CloudScraper to bypass CloudFlare protection, then pass it to requests_html to render the javascript content.

WeaveDB transaction ID

I designed a system where Doctors and Patient can actually meet each other in a decentralized manner, use weaveDB to save my project… But I created a dashboard where by if u have registered, u can automatically view your details and only u have access to those details, so I want to ask how do I use my transactioniD to fetch data from the weave DB collections

I consulted their documentation but nothing seems to be working at all

I have tried multiple things but nothing seemed to be working I use the get method from their documentation but nothing worked at all, pls help me if you are just seeing this message thank you very much and GOD bless you

Phone Verfication Auth is not allowing to Access data in Firestore

I am facing issue with Getting Data from Firestore

Error : FirebaseError: Missing or insufficient permissions.

After changing the rule to below

service cloud.firestore {
match /databases/{database}/documents {

match /{document=**} {
   allow read, write: if request.auth != null;
}
}
}

Below is the Function from where i am trying to Call the database

async handelSearch(searchTerm: any) {

onAuthStateChanged(this.auth, async (user) => {
  if (user) {
    // User is signed in, see the user's uid
    console.log(user.uid)
    const querySnapshot = await getDocs(q);
let temp: any[]=[]
querySnapshot.forEach((doc) => {
  // doc.data() is never undefined for query doc snapshots
  temp.push(doc.data())
});
this.serachBarService.MemberList.update(() => temp);


    // Access and modify user data here
  } else {
    console.log("No auth")
    // User is signed out
  }
});
}

I am successfully able to console log the User ID also Authentication seems working fine to me don’t know what’s missing while accessing the firestore.
I am working with Highly sensitive data here so can’t run database in Test mode

Any help is Appreciated, Thanks in Advance.

UPDATE :
I tested this in Emulator, Rule is working correctly there
enter image description here

Zoom on Touch devices, what exactly does it do?

Frankly, I don’t understand what is going on here.

  1. Page zoom in the address bar is still 100%
  2. If I use console.log to print width/height of window, screen or element they still have exactly the same values as they do at 100%, as if nothing is zoomed in at all.
  3. But when I look at it, the screen is clearly zoomed in!
    What is going here? How do I even detect this? I just want to implement scroll while dragging an image through a zoomed in (via touch) zone. But there is no way to say it’s zoomed in!
    Also, calling window/scrollBy with constant dx/dy in this zoomed in (via touch) zone does nothing! It only works when my pointer is on the real boundary of the zone, which is not even accessible when zoomed in (via touch).

I want to detect a typing status of my telegra bot user

updateUserTyping, messages.setTyping, and messages.setEncryptedTyping are the avaialble methods in telegram TLD library but these are all only avaible to Telegram API not for Telegram bot API.Is there any way to add similar feature in bot api also?

I also used this custom code trick but it did not worked,

async function pollMessages() {
try {
const response = await fetch(${API_URL}getUpdates?offset=${lastUpdateId + 1});
const data = await response.json();
if (data.ok && data.result.length > 0) {
for (const userMessage of data.result) {
if (userMessage.update_id > lastUpdateId) {
const message = userMessage.message;
const messageText = message.text;
const photoArray = message.photo;
const documentArray = message.document;
const videoArray = message.video;

                if (message.reply_to_message) {
                    const originalMessageText = message.reply_to_message.text;
                    if (originalMessageText) {
                        const identityKeyStart = originalMessageText.indexOf('(');
                        const identityKeyEnd = originalMessageText.indexOf(')');
                        const identityKey12 = originalMessageText.substring(identityKeyStart, identityKeyEnd + 1).trim();
                        const datePattern = /w+-d{2}-d{2} @ d{1,2}.d{2}.d{2} (AM|PM)/;

                        if (identityKey === identityKey12 && datePattern.test(identityKey12)) {
                            messageReceivedFromTeam = true;

                            // Handle different types of media
                            if (photoArray) {
                                const fileId = photoArray[photoArray.length - 1].file_id;
                                const fileResponse = await fetch(`${API_URL}getFile?file_id=${fileId}`);
                                const fileData = await fileResponse.json();
                                if (fileData.ok) {
                                    const filePath = fileData.result.file_path;
                                    const fileUrl = `https://api.telegram.org/file/bot${API_TOKEN}/${filePath}`;
                                    displayMessage(fileUrl, 'other', true);
                                }
                            } else if (videoArray) {
                                const fileId = videoArray.file_id;
                                const fileResponse = await fetch(`${API_URL}getFile?file_id=${fileId}`);
                                const fileData = await fileResponse.json();
                                if (fileData.ok) {
                                    const filePath = fileData.result.file_path;
                                    const fileUrl = `https://api.telegram.org/file/bot${API_TOKEN}/${filePath}`;
                                    displayMessage(fileUrl, 'other', false, true);
                                }
                            } else if (documentArray) {
                                const fileId = documentArray.file_id;
                                const fileResponse = await fetch(`${API_URL}getFile?file_id=${fileId}`);
                                const fileData = await fileResponse.json();
                                if (fileData.ok) {
                                    const filePath = fileData.result.file_path;
                                    const fileUrl = `https://api.telegram.org/file/bot${API_TOKEN}/${filePath}`;
                                    displayMessage(fileUrl, 'other', false, false, true, documentArray.file_name);
                                }
                            } else {
                                displayMessage(messageText, 'other');
                            }

                            lastUpdateId = userMessage.update_id;
                            hideTypingIndicator();  // Hide the typing indicator after receiving a message
                        }
                    }
                }
            }
        }
    }
} catch (error) {
    console.error('Error polling messages:', error);
}

}

Cypress unable to login and continues to load

I am attempting to create a simple Cypress test script to automate the user login for Emirates.com.

Login works when done manually, but continues to load when done through cypress.. I suspect something may be blocking the login via automation tool.

Need guidance on what it could be?

I have verified the following:

  1. Test code works.
  2. Network connections checked.
  3. Browser user agent checked.

Test Code:

/// <reference types="cypress" />
import Homepage from '../pages/homepage.cy.js';
import data from '../../fixtures/data.json';
import * as utils from '../../support/utils.js';
import 'cypress-iframe'
import 'cypress-xpath'
import Login from '../pages/login.cy.js';


describe('Homepage Functionality', () => {
  const homepage = new Homepage();
  const login = new Login();

  before(() => {
    cy.log('Opening Emirates URL');
    cy.visit('/', {
      onBeforeLoad: (win) => {
        Object.defineProperty(win.navigator, 'userAgent', {
          value: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36',
        });
      }
    });
    // homepage.visit(),
    homepage.verifyTitle(data.HOMEPAGE_EXPECTED_TITLE);
    homepage.handlePrivacyPopup()

  });

  it.only('Login to Emirates', () => {
    login.clickLoginIcon()
    homepage.verifyTitle(data.LOGINPAGE_EXPECTED_TITLE)
    cy.log(Cypress.env('USERNAME'));
    login.enterUsername();
    login.enterPassword();
    login.clickSubmit();
    utils.verifyElement(login.SELECTORS.loadingText)
    utils.verifyElement(login.SELECTORS.loadingSpinner)
    

pageObject Code:

import data from '../../fixtures/data.json';

class Login {
    constructor() {
        // Initializes selectors for UI elements on the login page.
        this.SELECTORS = {
            loginIcon: '//a[contains(@class, "js-login-link") and .//span[text()="Log in"]]',
            usernameField: '//span[@class="input-field__field"]//input[@id="sso-email"]',
            passwordField: '//input[@id="sso-password"]',
            submitButton: '//button[@id="login-button"]',
            loadingText: '//div[@class="login-form__action-btn"]//button[@id="login-button"]//p[@class="login-form__loading-label" and text()="Loading"]',
            loadingSpinner: '//div[contains(@class, "ek-spinner")]',
            profileIcon: '//li[@class="js-account-selector "]/a[@data-id="header_nav_icon"]',
        };
    }

    // Navigates to the Login page.
    clickLoginIcon() {
        cy.xpath(this.SELECTORS.loginIcon)
            .should('be.visible')
            .click();
    }

    // Enters the username into the input field.
    enterUsername() {
        cy.xpath(this.SELECTORS.usernameField)
           .should('be.visible')
         //   .wait(2000)
            .type(Cypress.env('USERNAME'));
    }

    // Enters the password into the input field.
    enterPassword() {
        cy.xpath(this.SELECTORS.passwordField)
           .should('be.visible')
            .type(Cypress.env('PASSWORD'), {force: true});
    }

    // Clicks the submit button to log in.
    clickSubmit() {
        cy.xpath(this.SELECTORS.submitButton)
            .should('be.visible')
            .click();
    }

Failed Test Capture

I am expecting the login to successfully login me into Emirates.com website.

Can’t use custom hooks inside ‘queryFn’ which is a property of ‘useQuery’ (tanstack query)

I here want to fetch all ‘products’ using react query BUT

  1. ‘build process’ fails when using custom hooks inside ‘useQuery’, so it throws error in ‘build process’ but it works perfectly fine during ‘development server’

const { data, isPending, isError, error } = useQuery({ queryKey: ["products"], queryFn: ({ signal }) => useHttp({ signal }), });
(Using signal to abort http request if user navigates to other page when request is being made)

Error message shown is the below one:
Error: React Hook "useHttp" is called in function "queryFn" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use".

Once again it works during development server but I’m not able to ‘build’ it due to the above error

Has there been changes in how JavaScript stores variables and debugging behavior? [closed]

I’ve noticed significant changes in how JavaScript seems to store and manage variables, especially when debugging.

Previously, I could easily distinguish between variables declared with var, let, and const in the browser’s debugger. var variables were under the global window object, while let and const were in the Script object. I could also access these variables directly using window.variableName.

However, this behavior seems to have changed. Now, I can’t find these variables under the window object, and they all appear under a modules object in the debugger. Additionally, var variables show up as undefined, while let and const have <Value unavailable>.

I’m confused about how this affects variable scope, especially regarding the Temporal Dead Zone (TDZ).

  • How does this new behavior work with the TDZ?
  • Where are these variables actually stored now?

Any insights or explanations would be greatly appreciated.

Node js vercel wss failed [closed]

wss://fg-buzzer.vercel.app/socket.io/?pass=&EIO=3&transport=websocket
websocket failed
webscoket error
So the buttons are not working for example page and other things load but the js script or idk what but its not working this is the github link of my test site https://github.com/furjac/fg-buzzer
this works flawless when i use in node index.js locally
this is the site vercel hosting https://fg-buzzer.vercel.app/
there is no index.html so you have to directly goto /user.html or /host.html or /board.html

I want this site working have a quiz contest soon so creating this to use it on that day thanks in advance

Nest command module only works when i pas AppModule to CommandFactory.run() function

I created a command line application using nest CommandRunner class,and also created a module named JobModule and provided the command file as provider in it.

import { CommandFactory } from 'nest-commander';
import { AppModule } from './app.module';
import { JobModule } from './job.module';

async function bootstrap() {
  console.log('BAR');
  await CommandFactory.run(JobModule);
}

bootstrap();

this is my jobmodule:

import { Module } from '@nestjs/common';
import { PrismaModule } from './infrastructure/database/prisma.module';
import { LoggerModule } from './common/utils/logger/logger.module';
import { OrderModule } from './modules/order/order.module';
import { VoucherModule } from './modules/voucher/voucher.module';
import { TbsVoucherCommand } from './infrastructure/jobs/tbs.voucher';

@Module({
  imports: [PrismaModule, OrderModule, VoucherModule],
  providers: [TbsVoucherCommand],
})
export class JobModule {}

and this is my class which extends command runner:

@Command({ name: 'tbs-voucher', description: 'Process TBS Voucher' })
export class TbsVoucherCommand extends CommandRunner {
  constructor(
    private readonly logger: LoggerService,
    private readonly prismaService: PrismaService,
    private readonly orderService: OrderService,
  ) {
    super();
  }

  async run(passedParams: string[], options?: Record<string, any>) {
    console.log('Foo');
    return this.processTbsVoucher();
  }
}

in this case only “BAR” gets logged, but when i pass AppModule which is the my main module,’BAR’ also gets logged.

import { CommandFactory } from 'nest-commander';
import { AppModule } from './app.module';
import { JobModule } from './job.module';

async function bootstrap() {
  console.log('BAR');
  await CommandFactory.run(AppModule);
}

bootstrap();

i also run this file after npm run build, with this command : node .distjob tbs-voucher

can someone explain why nest works like that? could it be because of resolving dependencies in the modules i imported inside of the job module?

How to fix ‘Module not found: Can’t resolve’ error in React?

I’m working on a React project, and after installing a new package, I’m getting the following error when trying to run my app:

*Module not found: Can't resolve 'module-name' in '/path/to/project'*

*I’ve tried reinstalling the node modules using npm install, clearing the cache with npm cache clean –force, and restarting my development server, but the error persists. The module is correctly listed in my package.json, and I can see it in the node_modules folder.

Has anyone faced a similar issue? How can I resolve this error?”*

optimized solution for a filtering a json array with sample set of data(object)

I’m trying to iterate json array (sampleData) with sample enum object (testSet) and achieve the desired result (OUTPUT) through Angular typeScript (Array of strings).

enter image description here

Note: I’m trying to map testSet object with sampleData errorCode and filterout the json with errorCode present in testSet and SORT the response in same testSet manner. But, couldn’t figure out an optimal solution. Can someone please help. Thanks in Advance.

Tried fitering, mapping, sorting but code assuming code will be complex to execute and time constraints. thinking of an optimal solution.

please find the codebase here : “https://jsfiddle.net/aj65dq9t/”