Media streams capturing issue in MV3 (chrome extension) with respect to constraints

Description
When using the getUserMedia API in Chrome to capture audio from specific Chrome tabs using the chromeMediaSource and chromeMediaSourceId constraints, the API is not behaving consistently. The issue manifests as the error “Uncaught (in promise) DOMException: Invalid state error.”

To Reproduce
Steps to reproduce the behavior:

Get the streamId from the desktopCapture API

chrome.desktopCapture.chooseDesktopMedia(
      ["tab", "audio"],
      tab,
      (streamId, options) => {});

Here, tab` argument consists of the tab info

Use the getUserMedia API to get the streams

navigator.mediaDevices.getUserMedia({
  audio: {
    mandatory: {
      chromeMediaSource: "desktop",
      chromeMediaSourceId: streamId,
    },
  },
  video: {
    optional: [],
    mandatory: {
      chromeMediaSource: "desktop",
      chromeMediaSourceId: streamId,
    },
  },
}).then((streams)=>{});

Here, the “Uncaught (in promise) DOMException: Invalid state error.” will occur

Expected behavior
The getUserMedia API should consistently capture audio from Chrome tabs using the specified chromeMediaSource and chromeMediaSourceId constraints without resulting in an “Invalid state error.”

OS : iOS
Browser : chrome
Version : 119.0.6045.199
Additional context
I am working on the chrome extension (Manifest Version-3) so using the getUserMedia API to get the streams from the particular streamId and as mentioned above facing the Issues while capturing the media.

For reference use the below doc for more info on the errors for the different constraints of the getUserMedia API tried
getUserMedia-DOC

My use case is that I want to capture the audios only from the tabs but need the feature like tab switching.
So I want to first bring up the below so that the user can select the tab to be captured :
enter image description here

After selecting the tab the user must get the UI of the capturing like below :
enter image description here

To acheive the above I tried using the follwoing chrome APIs :

  1. getUserMedia – The issue with this I am not able to capture the particular streamID
  2. getDisplayMedia – The issue with this is I am not able to remove the window sharing option as I only want the tab capturing options

ES6 export equivalent for conditional static require exports?

I have seen in many projects (like React), they use require() to conditionally re-export properties like so:

// index.js

if (process.env.NODE_ENV === 'production' {
  exports = require('./cjs/react.production.min.js')
} else {
  exports = require('./cjs/react.development.js')
}

I am trying to convert this to its equivalent valid ES6 syntax, preserving individual exported members (for tree shaking).

I have tried this and it works, but you cannot import individual members:

import * as prod from './cjs/react.production.min.js'
import * as dev from './cjs/react.development.js'

let exports = {}

if (process.env.NODE_ENV === 'production') {
  exports = prod
} else {
  exports = dev
}

export default exports

Is there an equivalent for the original using valid ES6 syntax?

I suppose with a smart enough compiler, the assigned keys within the nested modules could be propagated to the top level at build time like this:

import { value_1 as prod_value_1 } from './cjs/react.production.min.js'
import { value_1 as dev_value_1 } from './cjs/react.development.js'

let value_1 = undefined

if (process.env.NODE_ENV === 'production') {
  value_1 = prod_value_1
} else {
  value_1 = dev_value_1
}

export { value_1 /* value_2, etc */ }

Accessing an Angular micro frontend from the host app using module federation

I have created a microfrontend(mfe) in Angular using module federation.
Below are the steps that I used to create the mfe:

  1. I have run: ng new mfes –standalone false
  2. After navigating in the ‘mfes’ directory, I ran the command: ng generate application product-listing.
  3. I navigated in product-listing and ran the command: npm install @angular-architects/module-federation.
  4. A file called webpack.config.js was created.
    I modified the content of the file as follows:
const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
const mf = require("@angular-architects/module-federation/webpack");
const path = require("path");
const share = mf.share;

const sharedMappings = new mf.SharedMappings();
sharedMappings.register(
  path.join(__dirname, '../../tsconfig.json'),
  [/* mapped paths to share */]);

module.exports = {
  output: {
    uniqueName: "productListing",
    publicPath: "auto"
  },
  optimization: {
    runtimeChunk: false
  },
  resolve: {
    alias: {
      ...sharedMappings.getAliases(),
    }
  },
  experiments: {
    outputModule: true
  },
  plugins: [
    new ModuleFederationPlugin({
        library: { type: "module" },

        // For remotes (please adjust)
        name: "productListing",
        filename: "remoteEntry.js",
        exposes: {
            './ProductListingModule': './projects/product-listing/src/app/app.component.ts',
        },

        shared: share({
          "@angular/core": { singleton: true, strictVersion: true, requiredVersion: 'auto' },
          "@angular/common": { singleton: true, strictVersion: true, requiredVersion: 'auto' },
          "@angular/common/http": { singleton: true, strictVersion: true, requiredVersion: 'auto' },
          "@angular/router": { singleton: true, strictVersion: true, requiredVersion: 'auto' },

          ...sharedMappings.getDescriptors()
        })

    }),
    sharedMappings.getPlugin()
  ],
};

The folder structure of the ‘product-listing’ mfe is below:

enter image description here

In a different folder, I have created a host app which I called main-app, using the command: new new main-app –standalone false. I have also added module federation.
Below is the config in the file webpack.config.js

const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin");
const mf = require("@angular-architects/module-federation/webpack");
const path = require("path");
const share = mf.share;

const sharedMappings = new mf.SharedMappings();
sharedMappings.register(
  path.join(__dirname, 'tsconfig.json'),
  [/* mapped paths to share */]);

module.exports = {
  output: {
    uniqueName: "mainApp",
    publicPath: "auto"
  },
  optimization: {
    runtimeChunk: false
  },
  resolve: {
    alias: {
      ...sharedMappings.getAliases(),
    }
  },
  experiments: {
    outputModule: true
  },
  plugins: [
    new ModuleFederationPlugin({
        library: { type: "module" },

        // For hosts (please adjust)
        remotes: {
          "productListing": "productListing@http://localhost:3000/remoteEntry.js",

        },

        shared: share({
          "@angular/core": { singleton: true, strictVersion: true, requiredVersion: 'auto' },
          "@angular/common": { singleton: true, strictVersion: true, requiredVersion: 'auto' },
          "@angular/common/http": { singleton: true, strictVersion: true, requiredVersion: 'auto' },
          "@angular/router": { singleton: true, strictVersion: true, requiredVersion: 'auto' },

          ...sharedMappings.getDescriptors()
        })

    }),
    sharedMappings.getPlugin()
  ],
};

Below is the folder structure:

enter image description here

I have also added the route for this mfe in the app.module.ts. Please find the file below:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {RouterModule, Routes} from "@angular/router";
import { loadRemoteModule } from '@angular-architects/module-federation';


const routes: Routes = [
  { path: 'product-listing', loadChildren: () => loadRemoteModule(
      {
        type: "module",
        remoteEntry:"http://localhost:3000/remoteEntry.js",
        exposedModule: './ProductListingModule'
      }).then(m => m.ProductListingModule) },
  
];
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    RouterModule.forRoot(routes),
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

I am serving the mfe ‘product-listing’ and can be accessed via localhost:3000
I am running the main-app (host app) and it can be accessed via localhost:4000.
However, when I am accessing localhost:4000/product-listing, I am getting the following error:ERROR TypeError: Cannot read properties of undefined (reading 'ɵmod') in the console. The URL is also changed back to localhost:4000.

Color hue slider for color picker

Can you help me with this, I tried many different solutions, none of them worked, and nobody on stackflow knew why. So I deleted it, so can you try give me the code, for the hue slider in this color picker, the id of the hue slider is “Colorbar”, here is the code:

<!DOCTYPE html>
    <!-- This is based on DillingerLee's great template here:
    https://github.com/Team-Code/KA_Offline -->
    <html> 
     <head>
        <title>Color Picker</title> 
        <link rel="icon" href="../Top-Logo.png">
    </head>
    <style>
    body {font-family: "Helvetica", sans-serif;}
    .No-Underline {text-decoration: none;}
    h1 {
    text-align: center;
    }
    #Topbar {
    width: 100%;
    height: 75px;
    position: fixed;
    top: 0px;
    background-color: rgb(14, 5, 255)
    }
    #Topbar h1 {
    color: white;
    }
    #Pages {
    float: left;
    height: 870px;
    width: 200px;
    margin-right: 0px;
    border-right: 2px solid rgb(214, 212, 212);
    border-top: 2px solid rgb(214, 212, 212);
    border-bottom: 2px solid rgb(214, 212, 212)
    }
    #About {
    border-right: 2px solid rgb(214, 212, 212);
    border-top: 2px solid rgb(214, 212, 212);
    border-bottom: 2px solid rgb(214, 212, 212);
    height: 870px;
    width: 1700px;
    }
    #About h2 {
    text-align:center;
    }
    #About p {
    font-size: 1.1em;
    }
    .Image-Div {
    border-left: 2px solid rgb(214, 212, 212);
    border-top: 2px solid rgb(214, 212, 212);
    float: right;
    width: 13%;
    height: 92.3%;
    }
    .Text-Div {
    font-size: 1.1em;
    background-color: white;
    border-top: 2px solid rgb(214, 212, 212);
    border-bottom: 2px solid rgb(214, 212, 212);
    float: right;
    width: 75%;
    height: 92%;
    overflow: auto;
    text-align: center; 
    line-height: 250px;
    }
    .Text-Div * {
    margin-left: 13px;
    margin-right: 10px;
    }
    .Content-Button {
    background-color: white;
    border-top: 2px solid rgb(214, 212, 212);
    border-bottom: 0px;
    border-left: 0px;
    border-right: 0px;
    width: 221px;
    height: 50px;
    font-size: 1.3em;
    font-weight: bold;
    cursor: pointer;
    }
    .Content-Button:hover {
    background-color: rgb(219, 219, 219);
    }
    .Page-Button {
    background-color: white;
    border-top: 2px solid rgb(214, 212, 212);
    border-bottom: 0px;
    border-left: 0px;
    border-right: 0px;
    width: 200px;
    height: 50px;
    font-size: 1.3em;
    font-weight: bold;
    cursor: pointer;
    }
    .Page-Button:hover {
    background-color: rgb(219, 219, 219);
    }
    .Select-Button {
    background-color: rgb(180, 228, 237);
    color: rgb(22, 55, 222);
    border-left: 5px solid rgb(22, 55, 222);
    }
    .Select-Button:hover {
    background-color: rgb(149, 203, 240);
    }
    .Reload-Button {
    width: 125px;
    height: 45px;
    background-color: rgb(196, 196, 207);
    border-radius: 10px;
    border: 0px;
    font-weight: bold;
    font-size: 35px;
    color: white;
    cursor: pointer;
    margin-top: 0px;
    margin-bottom: 0px;
    line-height: 25px
    }
    .Reload-Button:hover {
    background-color: rgb(141, 141, 148);
    }
    .Warning {
    background-color: red;
    color: rgb(237, 222, 5);
    font-size: 1.3em;
    }
    #Color-Picker {
    display: flex;
    width: 630px;
    height: 300px;
    background-color: white;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
    padding: 20px;
    text-align: center;
    margin-left: auto;
    margin-right: auto;
    margin-top: 200px;
    line-height: 100px;
    }
    #color_canvas {
        border: 2px solid rgb(214, 212, 212);
    }
    #color_canvas:hover {
        border: 2px solid rgb(0, 0, 0);
    }
    #Colorbar {
        border: 2px solid rgb(214, 212, 212);
        height: 295px;
        width: 40px;
        margin: 0px;
    }
    #Colorbar:hover {
        border: 2px solid rgb(0, 0, 0);
    }
    #Color-Word {
    width: 230px;
    height: 100px;
    border: 2px solid rgb(214, 212, 212);
    background-color: white;
    margin-bottom: 20px;
    }
    #Color-Word:hover {
        border: 2px solid rgb(0, 0, 0);
    }
    #Color-Background {
    width: 230px;
    height: 172px;
    border: 2px solid rgb(214, 212, 212);
    background-color: white;
    }
    #Color-Background:hover {
        border: 2px solid rgb(0, 0, 0);
    }
    #marker {
        background: rgba(0, 0, 0, 0);
        border: 3px solid white;
        border-radius: 10px;
        box-shadow: 0 0 2px rgba(0, 0, 0, 0.3);
        display: none;
        position: absolute;
        top: 450px;
        left: 600px;
        width: 10px;
        height: 10px;
        cursor: pointer;
    }
    body:has(#marker:hover) #color_canvas {
        border: 2px solid rgb(0, 0, 0);
    }
    </style>

    <body>
    <div id="marker">
    </div>
    <div id="Topbar">
    <center>
    <h1><span>Project At All</span><h1>
    </center>
    </div>
    <h1>Information On Home Page</h1>
    <div id="Pages">
    <h2 style = "text-align: center;">Projects</h2>
    <a class="No-Underline" href="../index2.html"><button class="Page-Button">Home</button></a>
    <button class="Page-Button Select-Button">Color Picker</button>
    </div>
    <div id="About">
    <h2>Color Picker</h2>
        <div class="Image-Div">
        <h2 style = "text-align: center;">Contents</h2>
        <button class="Content-Button Select-Button">Color Picker Page</button>
        <a class="No-Underline" href="./Color_Information.html"><button class="Content-Button">What Is A Color Picker</button></a>
    <a class="No-Underline" href="./Color_Steps.html"><button class="Content-Button">Color Picker Creation Steps</button></a>
        </div>
    <div class="Text-Div">
        <div id="Color-Picker" style="text-align: left;">
        <canvas width="300px" height="300px" id="color_canvas"></canvas>
        <div style=" width:20px; margin: 0px; margin-right: 20px; margin-left: 10px;">
        <canvas id="Colorbar"></canvas>
        </div>
        <div>
        <div id="Color-Word" style="line-height: 20px;">
        <p style = "font-weight: bold; font-size: 1.2em;">RGB:<span id="RGBText"></span></p>
        <p style="font-weight: bold; font-size: 1.2em;">Hex:<span id="HexText"></span></p>
        </div>
        <div id="Color-Background"></div>
        </div>
        </div>
    
    </div>
    </body>
    
     
     <script>
        var colorCanvas = document.getElementById('color_canvas');
        var colorSlider = document.getElementById('Colorbar')
        var marker = document.getElementById('marker')
        var isDown = false;
        document.addEventListener('mousedown', function() {
        isDown = true;
        });

        document.addEventListener('mouseup', function() {
        isDown = false;
        });
var ColorCtx = colorCanvas .getContext('2d');  // This create a 2D context for the canvas
var SliderCtx = colorSlider .getContext('2d')

// Canvas Section
var color = 'rgba(0,0,255,1)';
let gradientH = ColorCtx .createLinearGradient(0, 0, ColorCtx .canvas.width, 0);
gradientH.addColorStop(0, '#fff');
gradientH.addColorStop(1, color);
ColorCtx .fillStyle = gradientH;
ColorCtx .fillRect(0, 0, ColorCtx .canvas.width, ColorCtx .canvas.height);


// Create a Vertical Gradient(white to black)
 let gradientV = ColorCtx .createLinearGradient(0, 0, 0, 300);
 gradientV.addColorStop(0, 'rgba(0,0,0,0)');
 gradientV.addColorStop(1, '#000');
 ColorCtx .fillStyle = gradientV;
 ColorCtx .fillRect(0, 0, ColorCtx .canvas.width, 
 ColorCtx .canvas.height);
 
    const selectedColor = document.getElementById("Color-Background");
    function rgb2hex(rgb) {
    rgb = rgb.match(/^rgb((d+),s*(d+),s*(d+))$/);
    function hex(x) {
    return ("0" + parseInt(x).toString(16)).slice(-2);
    }
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
    }
    function pick(event, destination) {
    if (isDown == true) {
        const bounding = colorCanvas.getBoundingClientRect();
        const x = event.clientX - bounding.x;
        const y = event.clientY - bounding.y;
        const pixel = ColorCtx.getImageData(x, y, 1, 1);
        const data = pixel.data;

        const rgb = `rgb(${data[0]}, ${data[1]}, ${data[2]})`;

        [red, green, blue] = rgb.substring(rgb.indexOf('(') + 1, rgb.lastIndexOf(')')).split(/,s*/),
        // passing the variables into the Object Literal; in this instance
        // we're passing in the variables which are the literal name of the
        // properties they define and which also contain the relevant value:
        colorObject = {
            red,
            green,
            blue
        };
        mousePosition = {
            x : event.clientX,
            y : event.clientY
        };
        destination.style.background = rgb;
        document.getElementById('RGBText').textContent = (red + ', ' + green + ', ' + blue);
        document.getElementById('HexText').textContent = rgb2hex(rgb);
        marker.style.display = "block";
        marker.style.left = (mousePosition.x - 5) + 'px';
        marker.style.top = (mousePosition.y - 5) + 'px';
        return rgb;
    };
};
function pick2(event, destination,) {
const bounding = colorCanvas.getBoundingClientRect();
const x = event.clientX - bounding.x;
const y = event.clientY - bounding.y;
const pixel = ColorCtx.getImageData(x, y, 1, 1);
const data = pixel.data;

const rgb = `rgb(${data[0]}, ${data[1]}, ${data[2]})`;

[red, green, blue] = rgb.substring(rgb.indexOf('(') + 1, rgb.lastIndexOf(')')).split(/,s*/),
// passing the variables into the Object Literal; in this instance
// we're passing in the variables which are the literal name of the
// properties they define and which also contain the relevant value:
colorObject = {
red,
green,
blue
};
mousePosition = {
x : event.clientX,
y : event.clientY
};
destination.style.background = rgb;
document.getElementById('RGBText').textContent = (red + ', ' + green + ', ' + blue);
document.getElementById('HexText').textContent = rgb2hex(rgb);
marker.style.display = "block";
marker.style.left = (mousePosition.x - 5) + 'px';
marker.style.top = (mousePosition.y - 5) + 'px';
return rgb;
};
colorCanvas.addEventListener("click", (event) => pick2(event, selectedColor))
colorCanvas.addEventListener("mousemove", (event) => pick(event, selectedColor))
//Slider Section
let gradient = SliderCtx .createLinearGradient(0, 0, 0, SliderCtx . canvas.height);
gradient.addColorStop(0, "rgb(255, 0, 0)");
gradient.addColorStop(0.15, "rgb(255, 0, 255)");
gradient.addColorStop(0.33, "rgb(0, 0, 255)");
gradient.addColorStop(0.49, "rgb(0, 255, 255)");
gradient.addColorStop(0.67, "rgb(0, 255, 0)");
gradient.addColorStop(0.84, "rgb(255, 255, 0)");
gradient.addColorStop(1, "rgb(255, 0, 0)");
SliderCtx .fillStyle = gradient;
SliderCtx .fillRect(0, 0, SliderCtx .canvas.width, SliderCtx .canvas.height);
     </script>

I tried to make the color hue slider work, but it didn’t so I restarted and din’t know where to start, so I am saking for a start code to help me

MERN for Multiplayer Game?

Is it possible to utilize the MERN stack to make a complex game using multiplayer/turn based modes-making maps/journal logs/generate scenes/dm ‘friends’?
Is there an easy way to do thing with MERN or is there a better way to implement these into a web app and PWA?
What are your ideas?

I have messed around with MERN and think it would be very complex.. Was sort of expecting it to be very complex, just need to know the best way to go about this project?

Unintuitive MixedContent error trace on my personal website

I have a portfolio website (https://github.com/ltbd78/portfolio) deployed on GitHub Pages (https://ltbd78.github.io/portfolio) and served on google domains (http://linsuhan.com). The insecure http://linsuhan.com site works fine but the secure https://linsuhan.come gets the following three MixedContent errors:

Mixed Content: The page at 'https://linsuhan.com/' was loaded over HTTPS, but requested an insecure script 'http://linsuhan.com/static/js/main.a0793265.js'. This request has been blocked; the content must be served over HTTPS.

Mixed Content: The page at 'https://linsuhan.com/' was loaded over HTTPS, but requested an insecure stylesheet 'http://linsuhan.com/static/css/main.f8417732.css'. This request has been blocked; the content must be served over HTTPS.

Mixed Content: The page at 'https://linsuhan.com/' was loaded over HTTPS, but requested an insecure favicon 'http://linsuhan.com/logo-l.png'. This request has been blocked; the content must be served over HTTPS.

I’ve been scratching my head the whole week on trying to debug where exactly exactly in my source code is this error trace coming from since I’m using ReactJS and the final build .js .css files differ drastically from the src .jsx and .scss files.

Is there a way to find out which line in my source code does this error reference?

How to generate custom tag/element(component) using insertAdjacentHTML in Vue

Using insertAdjacentHTML I can make div, span etc .. html element but cannot make custom tag forexample <myComponent> </myComponent>

Basically insertAdjacentHTML can generate html element, that’s I know but custom Component is also consisted with html tag. So I think there must be a way, generate custom element using like insertAdjacentHTML or else.

I tried test component and basic html element.
what I want is not generate html element but component.

code below is what I tried

“when someone click a button, then generate component” is my purpos

<template>
<button @click="test"></button>
</template>

<script setup>
import multiSelectComp from '@/views/utils/multiSelectComp'
function test(){
let tag = document.getElementById('test3');
  tag.insertAdjacentHTML("afterend", `<multiselect 
        :arg=true>
    </multiselect>`)
}
</script>

p5.js stuck on loading in the preload() function on web editor

I am using p5.js, and me and my friends are working on a game for fun. We are using the web editor. We have imported some assets using the preload function. This displays a loading screen. However, it never stops loading. Unfortunately, I can’t really put the code here, because of how much of it there is, but I can provide you guys with a snippet and a link.

Here is the link to our p5 sketch: https://editor.p5js.org/adsfzxc940/sketches/jkCZbn4oM

This is our preload function, what we think is the root of the problem:

function preload() {
  images = [
    loadImage("defensive.png"),
    loadImage("offensive.png"),
  ];

  sounds = [
    loadSound("blades.mp3"),
    loadSound("shiver.mp3"),
    loadSound("error.mp3"),
    loadSound("lies.mp3"),
  ];

  // Sound variable shortcuts
  music.push(sounds[0], sounds[1], sounds[3]);
  menuSong = music[2];
  error = sounds[2];
  lies = loadSound("lies.mp3");

  // Image variable shortcuts
  // baseImages.defensive = images[1];
  // baseImages.offensive = images[2];
}

All files are defined, as you can see either through the link or this image: https://i.stack.imgur.com/jZYtB.png

We have even tried checking the asset locations, but nothing seems to stop it from getting stuck on loading. The weird thing is that p5 doesn’t even tell us there are any errors. And we are almost certain that the preload function is the reason for this, because upon deleting it, the game runs fine.

Any help would be incredibly appreciated, as this has annoyed me for hours now and we don’t want to have to start over again. Note that me and the people who helped work on this with me are very new to JavaScript.

How to properly stub a function within a function module using sinon in JavaScript?

I keep trying to stub this function within a module in a format like so (myModule.js):

module.exports = function (config) {

    setUpModule(config);

    async function myFunction(parameters) {
        // logic...
    }

    return {
        myFunction,
    };
}

In my tests, I try to stub it like:

`beforeEach(() => {
    myFunctionStub = sinon.stub(myModule, 'myFunction').resolves(['apple', 'orange', 'grape']);
});

afterEach(() => {
    sinon.restore();
});`

Yet I keep getting: TypeError: Cannot stub non-existent property myFunction

Am I bringing in the function incorrectly? I have tried using the prototype keyword with the same result.

I have seen examples of using stub this way, and then using the instance of the module created to run tests on. I want to globally stub the function so that when other functions create their own instances of the module and run myFunction, that will return the stubbed value. I am quite new to stubbing with sinon, so maybe I am missing something obvious or misunderstanding the scope of what I can stub here.

I would appreciate any advice. Thank you!

Tried prototype keyword, stubbing as myModule()/myModule().prototype, but cannot get the function to be properly globally stubbed

When and where to use js modules? [closed]

I’ve read a little about them on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules but I’m still a unsure how exactly I should be splitting up my code. I’ve got functions that attach event listeners, functions feed into said event listeners, and even a couple of fetch calls that add elements to the webpage.

Everything is currently in one js file but I would like to break it up for organization and loading efficiency but I want to avoid possibly adding unnecessary delay to page functionality.

Any advise on this? When to use modules, what should be in a module, places I can see examples of this?

when Im trying to install react i get this error how to fix it and install react

npm ERR! code ENOTFOUND
npm ERR! syscall getaddrinfo
npm ERR! errno ENOTFOUND
npm ERR! network request to http://registry.npmjs.org/create-react-app failed, reason: getaddrinfo ENOTFOUND your_proxy_url
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network ‘proxy’ config is set properly. See: ‘npm help config’

npm ERR! A complete log of this run can be found in: C:UsersAraniAppDataLocalnpm-cache_logs2024-01-09T00_57_25_359Z-debug-0.log

i want a command to mitigate this issue

In Google map How to create custom area boundaries and check if given coordinates belongs to that area

I would like to define custom boundaries. E.g. would like to divide city in multiple areas say Area1, Area2 and so on.
I would like to save those custom areas in my DB and do search based on my DB data for area.

I know using draw line I can create Polygon.
I would like to check given coordinates belongs to which Area.

Is the draw line created polygon is best approach to create custom area boundaries?
How can I check whether given coordinates belongs to that area (Polygon) or not?

I have created polygon using draw line option of google map.
I am able to export KML file.

Not able to confirm should I save that KML file in my DB? Is it right approach?
Not able to check whether given coordinates belongs to custom areas.

Javascript set font size to fill width of page

I am trying to create a full-page web-based clock to be used by an embedded device. The idea is that the device will show a full screen with the clock in large display, and below that the current temperature, Farenheit and Celsius and a city name or code. The clock time and temperatures will be updated over time; the clock will simply scroll through the available cities repeatedly on 5-second intervals.

I’m having trouble getting the font sizing to work properly. The idea is that a smallish font will be set to get an initial size, then we’ll do the arithmetic to make the text fill 90% of the width. This is done in an iterative loop because offsetWidth is an integer value, so iterative processing should get us close enough to our goal.

There is a group division, and within that a division for time and a division for temperature. All three of these specify 100% width, which is what I want. And then the individual elements’ offsetWidths are applied against the division width to derive the font needed to fill that width.

Play-by-play, the initial “clock” offsetWidth with a 10-point font is 48 with a goal of 1259. The arithmetic correctly sets the fontsize to 236 (and change). Then we look at the temperature offset width, and before any arithmetic is done, it shows offsetWidth is already 1259, so the font is not manipulated. But that number is not correct; the offsetWidth should be more like 150 or so.

Also, the clock sizing seems to work only once (so it appears for about a half second), and then has the same problem as the temperature sizing. I don’t see any point where I fail to reset or where I reset incorrectly, so I am confused what’s happening here.

I have included the source (test.html and test.js) in hopes that someone can tell me where I might have gone wrong. I would appreciate your guidance.

test.html

<!DOCTYPE html>
<html lang='en' style="height:100%; width:100%; margin:0; padding:0">
    <head>
    <title>Full Screen Clock</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name='viewport' content ='width = device-width, initial-scale = 1, minimum-scale = 1, maximum-scale = 1, user-scalable = no, viewport-fit=cover' >
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="apple-mobile-web-app-title" content="Ampron Clock">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

    <style>
        /* Customizable font and colors */
        html {
            font-family: 'Courier' ;
            background:#000000;
            color: #91ff0f ;
        }
    </style>
</head>

<body style="display:flex; height:100%; width:100%; margin:0; padding:0; justify-content:center; align-items:center">
    <div style='height:100%; width: 100%; margin: 0 auto'>
        <div id='clockDiv' style='height:60%; width:100%; margin: 0 auto'>
            <span id="clocktext" style="font-kerning:none; text-align:center"></span>
        </div>
        <div id='tempDiv' style='width:100%; margin: 0 auto'>
            <span id="temptext" style="font-kerning:none; text-align:center"></span>
        </div>
    </div>

    <script src='test.js'></script>
</body>
</html>

test.js

    "use strict" ;
    const cycleLength = 5 ;
    const startFontSize = 10 ;
    const targetWidth = .9 ;
    var tempsTableElem = document.getElementById('temps') ;
    var timeElem = document.getElementById("clocktext") ;
    var tempElem = document.getElementById("temptext") ;
    var clockElem = document.getElementById("clockDiv") ;
    var timeFontSize ;
    var tempFontSize ;
    var cityTempArray ;



    function updateClock() {
        var d = new Date() ;

        var seconds = d.getSeconds() ;
        var cityCount = cityTempArray.length ;
        var showSeconds = (cityCount == 1) ;
        var showCity = (cityCount > 1) ;
        // We change cities (if applicable) every 5 seconds. So:
        //     If there are two cities, the cycle repeats every 10 seconds
        //     If there are three cities, the cycle repeats every 15 seconds
        //     four cities: 20 seconds
        // Therefore, we can use (seconds/5) modulus (number of cities) to get city index.
        // So if we are, say, 38 seconds into the minute and there are, say, 3 cities, then current city (from 0 to 2) is:
        //     Math.floor(38/5) % cityCount = 7 % 3 = 1 (0~4=0 5~9=1 10~14=2 15~19=0 22~24=1 25~29=2 30~34=0 35~39=1)
        // We will set maximum to 4 cities because it gets weird after that.  Anyway, that's enough, right?
        var currentCity = Math.floor(seconds/cycleLength) % cityCount ; // (0 through number-cities - 1)

        var cityCode = cityTempArray[currentCity][0] ;
        var farenheit = round(cityTempArray[currentCity][1], 0) ;
        var s = "" ;
        var celsius = round(5 / 9 * (farenheit - 32), 1) ;
        var colon = (showSeconds || d.getMilliseconds() < 500) ? ':' : ' ' ;
        s +=         (d.getHours()   < 10 ? "0" : "") + d.getHours()   ;
        s += colon + (d.getMinutes() < 10 ? "0" : "") + d.getMinutes() ;
        if (showSeconds)
            s += colon + (d.getSeconds() < 10 ? "0" : "") + d.getSeconds() ;

        timeElem.textContent = s ;
        s = farenheit + 'ºF ' + celsius + 'ºC' ;
        if (showCity)
            s += ' ' + cityCode ;
        tempElem.textContent = s ;

        updateTextSize() ;
        let time = 500 - d.getTime() % 500 + 20 ;
        setTimeout(updateClock, time) ;
        }



function updateTextSize() { // Attempt to fill the width of the page with clock text and temperature text
    tempFontSize = startFontSize ;
    timeFontSize = startFontSize ;
    for (var i = 0 ; i < 3 ; i++) {  // Iterate for better better convergence
        // We will hide the elements we're not sizing, so that they don't interfere
        tempElem.style.display = 'none' ;
        timeFontSize *= targetWidth / (timeElem.offsetWidth / clockElem.offsetWidth) ;
        timeElem.style.fontSize = timeFontSize + "pt" ;
        // We will hide the elements we're not sizing, so that they don't interfere
        timeElem.style.display = 'none' ;
        tempElem.style.display = 'block' ;
        tempFontSize *= targetWidth / (tempElem.offsetWidth / clockElem.offsetWidth) ;
        tempElem.style.fontSize = tempFontSize + 'pt' ;
        timeElem.style.display = 'block' ;
    }
}

function getTemps(tableElement) {
    cityTempArray = [ [ 'NewYork', 34 ], ['Brisbain', 76 ] ] ;
}



function round(value, precision) {
    var multiplier = Math.pow(10, precision || 0) ;
    return Math.round(value * multiplier) / multiplier ;
}



getTemps() ;
updateClock() ;
window.addEventListener("resize", updateTextSize) ;

How to use HTML button to call my javascript function then display result of javascript code which generates random token

So I’m working on an HTML page that contains a form where a user can send out an email invitation to join a website. I want a random token to be generated and sent along with the invitation, however first I want the user sending the invitation to be able to generate and see the token. Thus I’ve created a button in the HTML form to generate the token and I’m trying to get the button to call upon my token generator code I have written in Javascript and then display the generated token within the HTML form before the user submits the invitation email. Here is my HTML for the form and the token generator button is highlighted in bold.

<div class="form-group">
<form id="invitationForm" form action="https://getform.io/f/d59e4f74-57a0-412a-a77f-c100c59142d3" method="POST">
  <label class="col-md-4 control-label" for="textinput">Name</label>  
  <div class="col-md-4">
  <input id="textinput" name="textinput" type="text" placeholder="Full Name" class="form-control input-md" required="">
    
  </div>
</div>

<div class="form-group">
  <label class="col-md-4 control-label" for="email">Email</label>  
  <div class="col-md-4">
  <input id="email" name="email" type="email" placeholder="" class="form-control input-md" required>  
  </div>
    ** <button onclick="token()">Generate Token</button>
     <div id="result"></div>**
     <p></p>   
        <input type="submit" value="Send Invitation">
</div>

And here is my Javascript code to generate token

<script>
function token() {
const random = size => btoa(
  String.fromCharCode(
    ...crypto.getRandomValues(
      new Uint8Array(size)
    )
  )
).replaceAll('+', 'x').replaceAll('/', 'I').slice(0, size)

for (let i = 5; i--;) console.log(random(16))}
</script>

How do I get the token generator, upon clicking the button, to output the token to the HTML form (ideally in a text box above the “Send Invitation” button)? Thanks

I tried adding

`document.getElementById("result").innerHTML = "String.fromCharCode"'

to the javascript code to get it to output to the HTML however that did not work.

How to initialize an Uppy instance with an existing instance in Vue?

Currently I have a method that initializes Uppy to upload files, that works correctly, the problem I have is that since I have this component on a modal, when I open it again, a new instance is created, and if I had already opened it before and I uploaded an image, the previously uploaded files no longer appear.

I have to mention that I have the value returned by this method stored in a global variable that I can access as this.uppyInstance and that is stored when I open it and close the modal.

initializeUppy() {
            const uppy = new Uppy({
              restrictions: {
                maxNumberOfFiles: this.isUniq ? 1 : this.numberOfFiles,
                minNumberOfFiles: this.isUniq ? 1 : null,
                allowedFileTypes: ['image/jpeg', 'image/jpg', 'image/png']
              }
            })
            .use(Dashboard, {
                id: 'Dashboard',
                target: '#uppy-container',
                inline: true,
                locale: this.$i18n.locale === 'es' ? Spanish : English,
                note: this.note,
                autoOpenFileEditor: true,
                height: 525
              })
              .use(Webcam, { target: Dashboard })
              .use(DropTarget, { target: '#uppy-container' })
              .use(ImageEditor, {
                target: Dashboard,
                quality: 0.8,
                cropperOptions: {
                  viewMode: 1,
                  background: false,
                  autoCropArea: 1,
                  responsive: true,
                  croppedCanvasOptions: {},
                  cropBoxResizable: false,
                  initialAspectRatio: this.aspectRatio,
                  dragMode: 'move'
                },
                actions: {
                  cropSquare: false,
                  cropWidescreen: false,
                  cropWidescreenVertical: false
                },
                locale: this.$i18n.locale === 'es' ? Spanish : English
              });
      
            uppy.on('complete', result => {
              this.saveImages(result);
            });
      
            uppy.on('file-removed', (file, reason) => {
              this.removeFile(file);
            });
      
            this.uppyMounted = true;
    
            return uppy;
          }

What I need to do is that when I reopen the modal, the previous instance will be rendered again in the #uppy-container div, but I can’t do it since the div remains blank, I have tried this way:

const uppy = new Uppy(this.uppyInstance) but it doesn’t work, how can I do?