I have an input in my chrome extension popup, but i can not read the value of it on callback function. I need to read its value on button click(which is in popup as well) and persist it.
Category: javascript
Category Added in a WPeMatico Campaign
Distribution of n number of equi-distant point in polygon
I am creating a home styler using Three.JS. After creating a room that I want to allow user to generate x numbers of lights inside the room. The number of lights can be set by user. I want to automatically place the lights at the points that are equi-distant from each other as well as from the boundary line of the room (polygon).
Following are the approaches I used but have some limitations in it. The turf.js was used for these.
- Creating Voronoi Inside polygon: In this approach we can set the number of voronoi to be generated inside the polygon and placing the light on the center of each vornoi. But I voronoi sizes are not identical and are generated through random points inside polygon. Here is the code
clipVoronoiInsidePolygon() {
// Define your points
// Define a polygon to clip the Voronoi diagram to
this.clearAutoGeneratedLights();
const flatArray = this.convertVerticesToFlatArray();
if (flatArray.length == 0) return;
flatArray.push(flatArray[0]);
const polygon = turf.polygon([flatArray]);
const bbox = turf.bbox(polygon);
const points = turf.randomPoint(this.generateLight, { bbox: bbox });
// Generate the Voronoi diagram
const voronoiPolygons = turf.voronoi(points, { bbox: bbox });
// Clip each Voronoi cell with the polygon
const clippedVoronoiCells = voronoiPolygons.features
.map((cell) => turf.intersect(cell, polygon))
.filter(Boolean);
// Use clippedVoronoiCells as needed, for example, logging them
clippedVoronoiCells.map((vornoi) => {
// console.log(vornoi);
this.centerOfVornoi(vornoi?.geometry.coordinates);
});
}
- Cliping Square Grid inside Polygon: In this approach we the size of each box is identical and we can place the lights at the center of each box of the grid for making it equi-distant. But the number of boxes inside the polygon can not be adjusted. Hence user can not define the number of lights he needs.
clipSquareInsidePolygon() {
this.clearAutoGeneratedLights();
const flatArray = this.convertVerticesToFlatArray();
if (flatArray.length == 0) return;
flatArray.push(flatArray[0]);
const polygon = turf.polygon([flatArray]);
const targetCells = this.generateLight; // Assuming this is your desired number of cells
const area = turf.area(polygon);
// Calculate the side length of each cell to approximately achieve the target number of cells
// Assuming a square cell for simplicity: area of cell = side length^2
const desiredCellArea = area / targetCells; // in square meters
let sideLengthKilometers = Math.sqrt(desiredCellArea) / 1000; // Convert meters to kilometers
const bbox = turf.bbox(polygon);
const options = {
units: 'kilometers' as turf.Units,
size: sideLengthKilometers,
mask: polygon,
};
const squareGrid = turf.squareGrid(bbox, options.size, options);
squareGrid.features.map((box) =>
this.centerOfVornoi(box.geometry.coordinates)
);
}
This is what I have tried so far. About the tech I am using is Angular with Three JS.
How to solve “Showing nodemon is not recognized as an internal or external command”?
On running npm start my node js is not starting.
Showing this on npm start
‘nodemon’ is not recognized as an internal or external command, operable program or batch file.
I even checked my environment path.
I even ran ‘npm install -g nodemon’ but still not working.
Also ran
npm config get prefix
….But not working.
Previously i ran this command “npm config set bin-links false”
after that problem started to occur.
Attaching some images for reference.
enter image description here : path screenshot
enter image description here : screenshot of vs code
Possibility to design compiler using JavaScript
I’m about to design a compiler so I found it hard to implement it in Assembly Language using NASM assembler. Because it’s too much line of code so I design if I can use JavaScript to implement it.
I try to implement it using NASM assembler, but it’s too much line of code.
How to Maintain React Functionality for Overlays on Fullscreen Video Players in a Chrome Extension?
I’m developing a Chrome extension with React that overlays custom UI elements on top of video players across various websites. The extension works as expected in standard view, but I encounter issues when the video enters fullscreen mode. My overlay gets pushed to the background, behind the fullscreen video, making it invisible to the user.
To address this, I’ve implemented a workaround where I dynamically insert the overlay into the DOM tree of the fullscreen element, effectively bringing the overlay to the foreground. While this solves the visibility issue, it introduces a new problem: the loss of React’s event handling capabilities (e.g., onClick) on the overlay’s elements. It seems like once the overlay is manually inserted into the DOM, React no longer manages these elements, and thus, the React-specific event handlers stop working.
Here’s an example of how I’m adding the overlay to the fullscreen element:
if (fullscreenElement && canvasParentRef.current) {
fullscreenElement.appendChild(canvasParentRef.current);
}
Questions:
How can I add my React-based overlay to a fullscreen video in a way that keeps the React functionality intact, especially for event handlers like onClick?
Is there a more React-friendly approach to ensure that overlays remain functional and interactive atop fullscreen video players within a Chrome extension?
PS: Not a native english speaker. Used chatgpt to rephrase properly
Javascript. Writing data from asynchronous function
For my project, I am waiting and downloading data from Google Spreadsheet. My problem is that the LoadData function plays every time the user clicks on dropdown, because of this the LoadData function loads the same data from google tables again and the huge problem is that I can’t use this data anywhere else but the LoadData function which makes it huge and does other unnecessary things that could be done once. The solution is to unload the variable data into the global scope or at least load the data there from the LoadData function, but this is impossible because I need an Asynchronous function. What should I do?
Here is the code:
async function fetchData(){
const dataResponse = await fetch(urls);
const data = await dataResponse.json();
return data;
}
async function LoadData(selectedData = 0, loadThing = false)
{
let data = await fetchData();
if(loadThing)
{
//Load date to the DropDown
for(let i = 0; i < 5; i++)
MakeCoolDropdown(data.values[dataEnum.Date][i], i);
}
let keys = Object.keys(dataEnum);
for(let i = 1; i < 5; i++)
{
//Put Values from data to HTML page
let key = keys[i];
PutInHtml(key, data.values[dataEnum[key]][selectedData]);
}
}
let btn = document.getElementById("dropdown2_The_Movie");
btn.addEventListener('click', function()
{
let dropdownID = document.getElementById("dropdown2_The_Movie");
let dropdownValue = dropdownID.selectedIndex;
LoadData(dropdownValue);
});
How do I solve Uncaught TypeError: db._checkNotDeleted is not a function when using Firebase?
I am encountering a Uncaught Type Error when running my HTML code, specifically the error image db._checkNotDeleted is not a function error. This is occurring when trying to delete a task in my ToDo List Application(which stores variables on Firebase) and is an issue that I cannot seem to resolve.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To-Do List</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="todo-container">
<h1>My To-Do List</h1>
<input type="text" id="taskInput" placeholder="Add new task">
<button id="addButton">Add</button>
<ul id="taskList"></ul>
</div>
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-app.js";
import { getDatabase, ref, onValue, push, remove } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-database.js";
import { getStorage, ref as sRef, uploadString } from "https://www.gstatic.com/firebasejs/9.0.2/firebase-storage.js"; // Import storage reference and uploadString
// Initialize Firebase (replace with your own configuration)
const firebaseConfig = {
apiKey: "AIzaSyDC_cIVi_BfJmYEkEiWQsA6GAea6nJAcBg",
authDomain: "todo-list-b3003.firebaseapp.com",
projectId: "todo-list-b3003",
storageBucket: "todo-list-b3003.appspot.com",
messagingSenderId: "349349804975",
appId: "1:349349804975:web:bcee1b2d4e604bedbb0d5a",
databaseURL: "https://todo-list-b3003-default-rtdb.asia-southeast1.firebasedatabase.app",
};
const firebaseApp = initializeApp(firebaseConfig);
// Get a reference to the database service
const database = getDatabase();
// Get a reference to the storage service
const storage = getStorage(firebaseApp);
// Load tasks from the database when the page loads
window.onload = function() {
try {
const tasksRef = ref(database, 'tasks');
onValue(tasksRef, (snapshot) => {
const data = snapshot.val();
if (data) {
Object.entries(data).forEach(([taskId, taskText]) => {
addTaskToList(taskText, taskId);
});
}
});
} catch (error) {
console.error("Error loading tasks:", error);
}
};
function addTask() {
const taskInput = document.getElementById("taskInput");
const taskText = taskInput.value.trim();
if (taskText !== "") {
saveTaskToDatabase(taskText); // Save task to Firebase
taskInput.value = ""; // Clear input field
}
}
function deleteTask(taskId) {
console.log("Deleting task with ID:", taskId);
const tasksRef = ref(database, 'tasks');
const taskRef = ref(tasksRef, taskId);
remove(taskRef).then(() => {
console.log("Task deleted successfully.");
}).catch((error) => {
console.error("Error deleting task:", error);
});
}
function addTaskToList(taskText, taskId) {
const taskList = document.getElementById("taskList");
const newTask = document.createElement("li");
newTask.innerText = taskText;
newTask.dataset.taskId = taskId; // Assign Firebase ID to dataset
newTask.addEventListener("click", function() {
const taskId = this.dataset.taskId;
deleteTask(taskId); // Call the deleteTask function
this.remove();
});
taskList.appendChild(newTask);
}
function saveTaskToDatabase(taskText) {
const tasksRef = ref(database, 'tasks');
push(tasksRef, taskText);
}
// Add event listener to the button when the DOM is loaded
document.addEventListener("DOMContentLoaded", function() {
const addButton = document.getElementById("addButton");
addButton.addEventListener("click", addTask);
});
</script>
</body>
</html>
This is my code, and when running it I am encountering the error, please help me resolve this.
interaction.options.getString is not a function
I am trying to code a MusicBot for Discord in discord.js but when i try to execute the play command I always get interaction.options.getString is not a function. I searched in the Internet for this error couldn’t find anything.
My Code:
const { QueryType, useMainPlayer, useQueue } = require("discord-player");
const { ApplicationCommandOptionType, EmbedBuilder } = require("discord.js");
module.exports = {
name: "play",
description: "play a song!",
voiceChannel: true,
options: [
{
name: "song",
description: "the song you want to play",
type: ApplicationCommandOptionType.String,
required: true,
},
],
callback: async (interaction, client) => {
const player = useMainPlayer();
const song = interaction.options.getString("play");
};
I also tried the interaction.options.get command but doesn’t work either.
How to access Parent Variable from Function JS
What’s the correct way to access x?
let x = 5
const f = (n:number)=> {
let x = "Welcome";
return x * n // First x not second x
}
and what’s the correct technical name for this operation?
how to change data type in javascript input form?
I’m working on an apps script project with a spreadsheet as a database.
function getFormValues(formObject) {
/** ADD OR REMOVE VARIABLES ACCORDING TO YOUR FORM */
if (formObject.RecId && checkID(formObject.RecId)) {
var values = [
[formObject.RecId.toString(),
formObject.namaAdv,
formatDate(formObject.tanggal), // Format TANGGAL
formObject.toko,
formObject.product,
parseFloat(formObject.biayaIklan), // Parse BIAYA IKLAN as float
parseFloat(formObject.penjualanOrg), // Parse PENJUALAN ORGANIK as float
parseFloat(formObject.qtyOrg), // Parse QTY ORGANIK as float
parseFloat(formObject.penjualanAds), // Parse PENJUALAN ADS as float
parseFloat(formObject.qtyAds), // Parse QTY ADS as float
new Date().toLocaleString()
]
];
} else {
/** Reference https://webapps.stackexchange.com/a/51012/244121 */
var values = [
[new Date().getTime().toString(),
formObject.namaAdv,
formatDate(formObject.tanggal), // Format TANGGAL
formObject.toko,
formObject.product,
parseFloat(formObject.biayaIklan), // Parse BIAYA IKLAN as float
parseFloat(formObject.penjualanOrg), // Parse PENJUALAN ORGANIK as float
parseFloat(formObject.qtyOrg), // Parse QTY ORGANIK as float
parseFloat(formObject.penjualanAds), // Parse PENJUALAN ADS as float
parseFloat(formObject.qtyAds), // Parse QTY ADS as float
new Date().toLocaleString()
]
];
}
return values;
}
function formatDate(dateString) {
const date = new Date(dateString);
const day = ("0" + date.getDate()).slice(-2);
const month = ("0" + (date.getMonth() + 1)).slice(-2);
const year = date.getFullYear();
return `${day}/${month}/${year}`;
}
and I have an input form, one of which is of type date
<div class="col">
<label>TANGGAL<span style="color:red">*</span></label>
<div class="input-group input-group">
<span class="input-group-text"><span class="fa-solid fa-calendar"></span></span>
<input type="date" class="form-control" name="tanggal" id="tanggal" onfocus="(this.type = 'date')" required>
</div>
when the form is successfully submitted, but in the spreadsheet why does the date become plain text (example: when I input 03/23/2024, in the spreadsheet the date becomes ’03/23/2024)
enter image description here
How do I ensure that the date remains in the date format that I entered when inputting data?
bagaimana caranya agar tanggal tetap dalam format tanggal yang saya masukkan ketika input data?
Object object error when trying to save to local storage and display
Been trying to work out why I keep getting an output of [Output, output] instead of what the key is being saved as in local storage.
The function is meant to add a new body of text to a site and keep it there in local storage when the page is refreshed.
function saveEntry() {
console.log("saveEntry called with variables in scope:", {
key,
initialText,
isNewEntry,
textareaElement,
});
var data = text;
var item = makeItem("text", data);
localStorage.setItem(key, item);
console.log("saved item", key, "=", textareaElement.value);
}
textareaElement.addEventListener("change", saveEntry);
}
React router – loader
My git hub repo
.
i wrote bug description in issues section.
Basically, i don’t know why my dashboard loader function doesn’t run after creating user profile (Object), but main loader works fine.
(Sorry for my bad English).Thank you for your help.
My Express server is sending HTML instead of JSON when in production on vercel but it works on localhost in production
Title basically says it all, I’m making an app for students to rate their teachers but res.json() is sending a html file with just the nav bar, it’s weird because when I run the server on my Macbook it works and send json.
Here’s my backend index.js
console.clear();
const express = require('express');
const db = require('./config/db');
const cors = require('cors');
const cluster = require('cluster');
const bodyParser = require('body-parser');
const path = require('path');
require('colors');
require('dotenv').config();
app = express();
process.on('uncaughtException', function (err) {
console.log(err);
console.log('Node NOT Exiting...');
});
// app.use(express.static(path.join(__dirname, 'public')));
app.use(cors());
app.use(express.urlencoded({ extended: true }));
app.use(bodyParser.json());
db.connectDb();
app.get('/favicon.ico', (req, res) =>
res.sendFile(__dirname + '/public/favicon.ico')
);
app.use('/api/teachers', require('./routes/teacherRoutes'));
app.use('/api/ratings', require('./routes/ratingRoutes'));
if (process.env.NODE_ENV === 'production') {
// Static folder
app.use(express.static(__dirname + '/public/'));
// Handle SPA
app.get('/', (req, res) => res.sendFile(__dirname + '/public/index.html'));
}
console.log(__dirname);
app.listen(process.env.PORT, () => {
console.log(`server listening on port ${process.env.PORT}`.dim.bold);
});
the “/favicon.ico” works even in Vercel, the lines to handle the frontend work(I think) yet the “/api/teachers” and the other ones don’t work heres how the “/api/teachers” work – also keep in mind I’m focusing on the teacher endpoint but none of them work:
//get all teachers
const get = async (req, res) => {
res.json(await Teacher.find());
};
const post = async (req, res) => {
if (req.body.name) {
if ((await Teacher.exists({ name: req.body.name })) == null) {
res.json(await Teacher.create({ name: req.body.name }));
} else {
res.status(400).json({
message:
'The teacher you are trying to add is already in the database.',
});
}
} else {
res
.status(400)
.json({ message: 'Please add a teacher name to your request' });
}
};
module.exports = {
get,
post,
};
here’s some of my vercel config:
"require": "@vercel/static-build",
"requirePath": "/usr/local/lib/node_modules/vercel/node_modules/@vercel/static-build/dist/index",
"apiVersion": 2,
"src": "package.json",
"use": "@vercel/static-build",
"config": {
"zeroConfig": true,
"framework": "vue",
"installCommand": "npm install",
"buildCommand": "npm run build",
"outputDirectory": "/backend/public"
}
video.audioTracks is not working as expected for large video
From MDN Web Platform Experimental Features, It seems that it is possible to control a dual audio video’s Audio Track Selection using javascript. I enabled the chrome flag option and then tested with a 720p dual audio 20 minutes video. when I execute video.audioTracks, I see 2 audio tracks. But After that, If I try with a 2 hour 720p dual audio video, sometimes I see only 1 audio track and sometimes 0 audio tracks. What’s the problem here? Is there any problem with the video meta data or something? I’m sure that both of the video are dual audio. Here is a Fiddle: https://jsfiddle.net/dzx98no4/3/
How do I prevent my Google Map from resetting when parent component’s state is updated?
I need to prevent my Google Map from reverting to its original center and zoom settings every time its parent component re-renders.
I have a parent component that contains two main child components: a Google Map and a sidebar. On the screen it looks like this:
My intention is to populate the sidebar with information when a particular marker is clicked. Here’s the code:
PARENT:
import React, { useState } from "react";
import { styled } from "@mui/material/styles";
import MapComponent from "../Components/Map2";
export default function ACA() {
const [info, setInfo] = useState(null);
const FlexContainer = styled("div")(({ theme }) => ({
width: "98vw",
display: "flex",
justifyContent: "space-between",
alignItems: "center",
padding: 4,
[theme.breakpoints.down("md")]: {
flexDirection: "column",
},
}));
const updateSidebar = (elec) => {
setInfo(elec);
};
return (
<div
style={{
minHeight: "100vh",
minWidth: "100vw",
background: "linear-gradient(to bottom, black, midnightblue)",
display: "flex",
flexDirection: "column",
alignItems: "center",
paddingTop: 10,
}}
>
<FlexContainer>
<MapComponent updateSidebar={updateSidebar} />
<div
style={{
height: "650px",
maxHeight: "80vh",
width: "650px",
maxWidth: "98vw",
border: "2px solid black",
backgroundColor: "whitesmoke",
borderRadius: 8,
}}
>
<h4>{info}</h4>
</div>
</FlexContainer>
</div>
);
}
MAPCOMPONENT
import React, { useEffect, useState } from "react";
import { APIProvider, Map, AdvancedMarker } from "@vis.gl/react-google-maps";
import Axios from "axios";
export default function MapComponent({ updateSidebar }) {
const [markers, setMarkers] = useState([]);
useEffect(() => {
const getElectorates = async () => {
try {
const elecs = await Axios.get("http://localhost:3930/admin/getMapData");
setMarkers(elecs.data);
} catch (err) {
console.log(err);
}
};
getElectorates();
}, []);
return (
<APIProvider apiKey="<redacted>">
<Map
style={{
width: "650px",
height: "650px",
maxWidth: "80vw",
maxHeight: "80vh",
}}
defaultCenter={{ lat: -23.698, lng: 133.8807 }}
defaultZoom={4}
gestureHandling={"greedy"}
disableDefaultUI={true}
mapId="<redacted>"
>
{markers.map((el, i) => {
return (
<AdvancedMarker
position={el.coords}
key={i}
onClick={() => {
updateSidebar(el.electorate);
}}
/>
);
})}
</Map>
</APIProvider>
);
}
The issue is that whenever I click on a marker and execute the updateSidebar function, the parent component’s state is updated which in turn causes the map to revert to its original center and zoom settings. How can I prevent this from happening?
