How to hide the mouse cursor in screen capture using getDisplayMedia in JavaScript?

I’m trying to hide the mouse cursor during a screen capture session initiated via JavaScript’s getDisplayMedia(). The goal is to record the screen without showing the mouse cursor in the final video output. Despite setting the cursor option to “never” in the getDisplayMedia options, the cursor still appears in the recording. Here’s what I’ve tried:

async function startScreenRecording() {
  try {
    const displayMediaOptions = {
      video: {
        cursor: "never"
      },
      audio: true
    };
console.log(navigator.mediaDevices.getSupportedConstraints());
  if (navigator.mediaDevices.getSupportedConstraints().cursor) {
    console.log("Cursor constraint is supported.");
} else {
    console.log("Cursor constraint is not supported.");
}
    console.log("Display media options:", displayMediaOptions);
    const displayStream = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions);
    console.log("Display stream:", displayStream);

    handleMediaStream(displayStream);
  } catch ( error ) {
    console.error("Error capturing media.", error);
  }
}

function handleMediaStream(stream) {
  // Handling the media stream (omitted for brevity)
}

document.addEventListener("DOMContentLoaded", () => {
  startScreenRecording();
});

Now cursor is no longer supported when I log the navigator.mediaDevices.getSupportedConstraints() even though the MDN docs still have it here.

I tried using the following code to hide the cursor

document.addEventListener('DOMContentLoaded', () => {
    const bodyElement = document.querySelector('body');
    if (bodyElement) {
        bodyElement.style.cursor = 'none';
    }
});```
But this solution removes the cursor while my screen is being captured. 

Any alternative methods or workarounds to effectively hide the cursor during screen captures?

Add large data to the footer in jsPDF

I want to create a customized footer using jsPDF.

This footer may contain a large amount of data, so I want the content above the footer to automatically flow to the next page.

I am using an auto table to set the footer, but it is not producing the desired results.

autoTable(doc, {
  theme: 'plain',
  tableLineColor: [0, 0, 0],
  tableWidth: 175,
  startY: 277,
  body: [
    [{
      content: (this.orgDetailsObj.terms != undefined ? this.orgDetailsObj.terms : ''),
      styles: {
        halign: 'center',
        valign:'middle',
        fontSize: 8,
        textColor: 'black',
        fillColor:'white',
        // tableLineColor: [0, 0, 0],
        // tableWidth: 100,
        overflow:'linebreak',
      },
    }],
  ]
})

Difference between the two rules of react hooks

I was reading through their docs and found the below

Rules of hooks:

✅ Call them at the top level in the body of a function component.
✅ Call them at the top level in the body of a custom Hook.
function Counter() {
  // ✅ Good: top-level in a function component
  const [count, setCount] = useState(0);
  // ...
}

function useWindowWidth() {
  // ✅ Good: top-level in a custom Hook
  const [width, setWidth] = useState(window.innerWidth);
  // ...
}

My question is, what is the difference between the first and the second rule. The first rule itself covers what the second rule is telling.

How to save a csv file with correct encoding using capacitor

I have a nuxt app and using capacitor to create a mobile version app. Currently I want to save a csv file in mobile app (android). Here is my implementation so far:

const csvData = [
    ["創建日期", "賬目類型", "標題"],
    ["2024-03-22", "收入", "發票測試2"]
];

// Convert the CSV data to a CSV string
const csvString = csvData.map(row => row.join(',')).join('n');

// Write the encoded data to a file
const filename = 'data.csv';
const file = await Filesystem.writeFile({
    path: filename,
    data: csvString,
    directory: Directory.Documents,
    encoding: Encoding.UTF8
});

await FileOpener.open({
    filePath: file.uri,
    contentType: 'text/csv',
});

The output csv result doesn’t encoded correctly like this :

enter image description here

Anyone can help?

Use JavaScript TradingView Widget in Blazor razor page, possible?

try to use Widget as it is from Trading View in test Blazor razor page. Chart appearing, but I can’t change parameters in code, since compilator does not accept anything after src attribute as on the picture.

Screen

Is it possible to inject parameters, so I could change e.g. Symbol?

Thanks!

I also, tried to save JS code to separate file and call it like
await JSRuntime.InvokeVoidAsync("./script/tv.js");

but nothing happened.

Web Scraping by puppeteer

I am writing a html to scrape data by puppeteer from internet with the code below:

const puppeteer = require('puppeteer');

(async ()=>
{
    const browser = await puppeteer.launch()
    const page = await browser.newPage()

    await page.goto("https://www.info.gov.hk/gia/wr/202404/26.htm")

    const bulletin_urls = await page.$$('div.leftBody');

    for(const bulletin_url of bulletin_urls)
    {
        try
        {
            const bulletin_name = await page.evaluate(el => el.textContent, bulletin_url)
            console.log(bulletin_name)

            const single_url = await page.evaluate(el => el.getAttribute("href"), bulletin_url)
            console.log(single_url) 
        }
        catch(err)
        {
        
        }
    }
    await browser.close()
}) ();

I want to scrape 2 information of ALL PRESS WEATHER:

  1. the name of the bulletins
  2. the url of the Hyperlink.

I succeed when scraping 1 while fail at 2. What I get is simply null. I try to amend my code to

const single_url = await page.evaluate(el => el.querySelector(".NEW").getAttribute("href"), bulletin_url)
console.log(single_url)

However, it just returns me the first but not all url. What shall I do to collect all the url of the hyperlink at one command? Any suggestion will be appreciated.

getting inconsistent values on my postgres database

I had set up a cron which will update my table in the postgres database by fetching values from redis , the cron runs every 10 minutes . The values will be updated in the DB if same date data is present in the redis , otherwise will be updated with new value in the redis , Here is the code

const CacheUtils = require('../../utils/cache-utils');
const { DateTime } = require('luxon');
const {bookshelf} = require('../../schema/knex');
const googleLeadsSearchDailyEntries = require('../../schema/models/google-leads-search-daily-entries');

module.exports = class GoogleLeadFinder {
  static async googleLeadSearchUpsert() {
    
    const dailyCount = await this._getDataFromRedis();
    
    if (dailyCount.length === 0) {
      return;
    }

     await bookshelf
      .transaction(async trans => {
      const uniqueConstraint = `("userId","orgId","quotaDate")`;
      const params = {
        table: 'googleLeadsSearchDailyEntries',
        objects: dailyCount,
        constraint: uniqueConstraint
      };
      const action = `UPDATE SET "dailySearch"=EXCLUDED."dailySearch","updatedAt" = NOW()`;
     await googleLeadsSearchDailyEntries.upsert(params, trans,action);
      })
  }
  static async _getDataFromRedis() {
    const todayDate = DateTime.local();
    const client = await CacheUtils.getClient();
    const results = [];
    const filterCondition = `googleleads-userdaycountval-${todayDate.day}-${todayDate.month}-${todayDate.year}-*`;
    const  keys = await client.keysAsync(filterCondition);
    for (const key of keys) {
      const fetchDataFromKey = key.match(/d+/g).map(numStr => parseInt(numStr));
      const dailySearch = parseInt(await client.getAsync(key));
      results.push({ userId: fetchDataFromKey[3], orgId: fetchDataFromKey[4], dailySearch, quotaDate: todayDate.toISODate() });
    }
    return results;
  }
};

the code is running on my EC2 instance , and the database is on my aws rds check the image

as you can see on the image , cron is still updating till 26-04-2024(updatedAt) when the quota date is of 25-04-2024 , it should’nt have updated that

i want the cron to stop updating the data of the tuple whose quota date have been passed , working as expected on my local but not showing consistent results on stage environment
(Note : i have defined userId,orgId,quotaDate as unique fields)

Why doesnt the table get populated with the api response?

Ok. I have tried debugging this for hours. I call a fetch api and have verified that it returns the correct response formatted in the correct way, with all the keys and in array format compatible with the map function. However, the table when rendered appears to be missing the content of the body. Any ideas?

import React, { useEffect, useState, useContext } from 'react';
import "../App.css";
import { UserContext } from '../UserContext';

export function Watchlist() {
  const { user, logout } = useContext(UserContext);
  const [watchlist, setWatchlist] = useState([]);
  useEffect(() => {
    fetch(`http://127.0.0.1:8000/watchlist?user_id=${encodeURIComponent(user.id)}`)
      .then(response => response.json())
      .then(json => {
        setWatchlist(json)
      }
      ).catch(error => console.error(error));
  }, [user]);
  return(
    <table>
        <thead>
            <tr>
            <th>Ticker</th>
            <th>Name</th>
            <th>Last Price</th>
            </tr>
        </thead>
        <tbody>
            {watchlist && watchlist.map((s) => {
            <tr>
                <td>{s.ticker}</td>
                <td>{s.name}</td>
                <td>{s.last_price}</td>
            </tr>})}
        </tbody>
    </table>
  );
};

Eraser completely makes the Canvas white

main.js:

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

let isDrawing = false;
let lastX = 0;
let lastY = 0;
const AXIS_LENGTH = 50; // Length of the axis lines
let mouseX;
let mouseY;

// history so we can always redraw
var points = []
var allPoints = []
var invertedX, invertedY

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

function startDrawing(e) {
  isDrawing = true;
  [lastX, lastY] = [canvas.width - (e.pageX - canvas.offsetLeft), canvas.height - (e.pageY - canvas.offsetTop)];
  points = []
  allPoints.push(points)
  points.push([lastX, lastY])


}

function draw(e) {
  if (!isDrawing) return;

  const x = canvas.width - (e.pageX - canvas.offsetLeft);
  const y = canvas.height - (e.pageY - canvas.offsetTop);

  [lastX, lastY] = [x, y];
  points.push([lastX, lastY])

}

function stopDrawing() {
  isDrawing = false;
}


function clearCanvas() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
}

function resizeCanvas() {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
}

function drawAllPoints() {
  allPoints.forEach(drawPoints)

}

function drawPoints(points) {

  if (points.length) {
    ctx.save()
    ctx.strokeStyle = 'black';
    ctx.lineWidth = 5;
    ctx.lineCap = 'round';
    ctx.beginPath();
    ctx.moveTo(points[0][0], points[0][1]);
    for (var i = 1; i < points.length; i++) {
      ctx.lineTo(points[i][0], points[i][1]);
      ctx.stroke();

    }
    ctx.restore()
  }
}

function drawEverything() {
  clearCanvas()
  drawAxis();
  drawAllPoints()

}

function drawAxis() {

  mouseX = invertedX
  mouseY = invertedY
  // Draw vertical axis line
  ctx.save()
  ctx.beginPath();
  ctx.moveTo(mouseX, mouseY - AXIS_LENGTH / 2);
  ctx.lineTo(mouseX, mouseY + AXIS_LENGTH / 2);
  ctx.stroke();

  // Draw horizontal axis line
  ctx.beginPath();
  ctx.moveTo(mouseX - AXIS_LENGTH / 2, mouseY);
  ctx.lineTo(mouseX + AXIS_LENGTH / 2, mouseY);
  ctx.stroke();
  ctx.restore()
}


canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDrawing);
canvas.addEventListener('mouseout', stopDrawing);
canvas.addEventListener('touchstart', (e) => {
  e.preventDefault();
  startDrawing(e.touches[0]);
});
canvas.addEventListener('touchmove', (e) => {
  e.preventDefault();
  draw(e.touches[0]);
});
canvas.addEventListener('touchend', stopDrawing);
window.addEventListener('resize', resizeCanvas);
document.addEventListener("mousemove", function(event) {
  const mouseX = event.clientX;
  const mouseY = event.clientY;

  invertedX = window.innerWidth - mouseX;
  invertedY = window.innerHeight - mouseY;

  drawEverything()
});

When I tried to erase the canvas by clicking the erase button, the every stroke in the canvas becomes white. I also have a cross hair thing that shows where the stroke is to be drawn. The controls are inverted. I used if else for the draw and erase. I used white color for the stroke which makes as the eraser tool. But when I click the btn and tried to drag, everything turns white but again clicking the btn makes evrything turns black.

Material UI import leading to “You may need an appropriate loader to handle this file type.”

Getting the following compilation error on just adding an import statement for material UI button component.

Failed to compile.

./node_modules/@lit/reactive-element/decorators/query-async.js 10:56
Module parse failed: Unexpected token (10:56)
You may need an appropriate loader to handle this file type.
|   return (n, e) => t(n, e, {
|     async get() {
>       return await this.updateComplete, this.renderRoot?.querySelector(r) ?? null;
|     }
|   });

here is my import statement

import '@material/web/button/filled-button.js';

without that import , it works perfectly..

I am using "@material/web": "^1.4.1", dependency.

I am stuck in this.. How can i proceed here?

PS: i am new to react, apologies if i have done silly mistakes!

There is some way to apply a custom mask to a FormKit field? I want to write a custom mask

how can I add a mask to the value of this field while the user is typing?

<FormKit
  type="text"
  name="postalcode"
  label="Postal Code"
  placeholder="Insert a postal code"
  validation="required|length:9|matches:/^d{5}-d{3}$/"
/>

when the user inputs “123456”, the value should be masked to “12345-6” until it reachs the maxlength of 9 characters

I’ve tried with @input event, but it always ends with a infinite recursive call

Why is threejs lighting fun such as pointlight and ambientlight not working with version “three”: “^0.164.1”

I was doing my very first threejs small project with vite and threejs library

I added these light function in js file,

`// emit light evenly in all directions from specific point in space
const pointLight = new Three.PointLight( 0xff0000, 1, 100 );
pointLight.position.set(5, 5, 5);



// to spread the lighting across the entire scene
const ambientLight = new Three.AmbientLight(0xffffff);
scene.add(pointLight, ambientLight);`

Inside of package.json,

{
  "name": "three-demo",
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "serve": "vite preview"
  },
  "devDependencies": {
    "vite": "^5.2.0"
    
  },
  "dependencies": {
    "three": "^0.128.0"
  }
}

The problem is that the lighting function works perfectly with three dependencies “three”: “^0.128.0” but when changes to latest version “three”: “^0.164.1” and run npm install, then the lighting function not working

JavaScript extends

function Animal() {}

function Rabbit() {}
Rabbit.prototype = Object.create(Animal.prototype);
Rabbit.prototype.constructor = Rabbit;

class Rabbit extends Animal {}

console.log(Object.getPrototypeOf(Rabbit) === Animal);

Why do they say these two ways are the same, but there is this difference