Moving to Bottom of iframe after reloading it in 5 milliseconds interval

   window.setInterval("reloadIFrame();",500);
    function reloadIFrame() {            
        document.getElementById("myIframe").src="/chatbox/";
        //scrollTop = document.getElementById("myIframe").contentWindow.document.body.scrollTop;
        document.getElementById('myIframe').contentWindow.scrollTo(1000000,1000000);
        
        }

The fucntion ScrollTo is not working and it does not scroll to bottom
I tried searching other questions too but none of them work.Please give me a simple javascript solution without any Jquery or React.

Have I reached the maximum limit of iframes per page?

Is there a way of displaying more than 1000 iframes per page? I thought there were no upper limit, but I seem to have found it.

I am developing a hybrid mobile app where I display iframes upon request. These iframes are held within numbered spans from 1 to 1200. However, when spans bigger than 1000 are requested, the iframes are not displayed.

Let me illustrate with some code:

    <span id="1000" style="display:none;">
        <br><br><br>
        <span style="display:block;margin-left:auto;margin-right:auto;width:70%;-webkit-filter: blur(5px);-moz-filter: blur(5px);-o-filter: blur(5px);-ms-filter: blur(5px);filter: blur(5px);">
            <iframe style="border-radius:12px" src="https://open.spotify.com/embed/track/tracktokenhere1"
                width="100%" height="152" frameBorder="0" allowfullscreen=""
                allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture"
                loading="lazy"></iframe>
        </span><br>
        <div class="flip3D" onclick="flipCard()" style="margin: 0 auto;">
            <div class="card">
                  <!-- This content is always displayed when requested -->
            </div>
        </div>
    </span>
    <span id="1001" style="display:none;">
        <br><br><br>
        <span style="display:block;margin-left:auto;margin-right:auto;width:70%;-webkit-filter: blur(5px);-moz-filter: blur(5px);-o-filter: blur(5px);-ms-filter: blur(5px);filter: blur(5px);">
            <iframe style="border-radius:12px" src="https://open.spotify.com/embed/track/tracktokenhere2"
                width="100%" height="152" frameBorder="0" allowfullscreen=""
                allow="autoplay; clipboard-write; encrypted-media; fullscreen; picture-in-picture"
                loading="lazy"></iframe>
        </span><br>
        <div class="flip3D" onclick="flipCard()" style="margin: 0 auto;">
            <div class="card">
                  <!-- This content is always displayed when requested -->
            </div>
        </div>
    </span>

So, when I request the span id=”1000″ I see the Spotify content without any problem. However, when I request id=”1001″ I can see the rest of the content of the span, but the iframe content is missing.

At first, I thought that there were something in the id=”1001″ that was wrong, but I commented out the id=”1000″ and the id=”1001″ became ‘visible’. So I concluded that there is a maximum limit on the iframes display.

How can I get rid of this limit?

I have no problems on loading time, I have that fixed.

How to check User Status (Online/Offline) in firebase v9 using React

I Have made one chat application, i need to display user status (offline, online) and he gets disconnects, window/tab or logouts in firebase v9

firebase.js

import { initializeApp } from 'firebase/app';
import { getAuth } from 'firebase/auth';
import { getStorage } from 'firebase/storage';
import { getFirestore } from 'firebase/firestore';
import { getDatabase } from 'firebase/database';

const firebaseConfig = {
  apiKey: apikey,
  authDomain: 'xxxxx.firebaseapp.com',
  projectId: 'xxxx',
  storageBucket: 'xxxx.appspot.com',
  messagingSenderId: 'xxxxxx',
  appId: '1:xxxxxxxx:web:xxxxxxx',
};

export const app = initializeApp(firebaseConfig);
export const auth = getAuth();
export const storage = getStorage();
export const db = getFirestore();
export const firebaseDb = getDatabase(app);

Added firebase chat db

enter image description here

This is what I have tried but not working I guess (im new to firebase)

useEffect(() => {
    const db = getDatabase();
    const uid = '3bEw4VqpMieSzR8NBfDz6XqG33l1';
    const myConnectionsRef = refs(db, 'users', uid);
    console.log(myConnectionsRef, 'myConnectionsRef');
    onValue(myConnectionsRef, (snap) => {
      console.log(snap, 'snap');
      if (snap.val() === true) {
       // We're connected (or reconnected)! Do anything here that should happen only if 
        online (or on reconnect)
        const con = push(myConnectionsRef);
        console.log('hi', con);
        // When I disconnect, remove this device
        onDisconnect(con).remove();

        // Add this device to my connections list
        // this value could contain info about the device or a timestamp too
        set(con, true);

        // When I disconnect, update the last time I was seen online
        onDisconnect(lastOnlineRef).set(serverTimestamp());
      }
    });

  }, []);

Infer type based on values of dynamic object

I want to get keys to autocomplete in my IDE. The keys are based on URLPatternComponentResult['groups']:

export interface URLPatternComponentResult {
  input: string;
  groups: {
    [key: string]: string | undefined;
  };
}

In my code, I can register new web routes like so:

route.push({
  pathname: "/about/:name/:age",
  handler: (groups: DynamicGroups) => {
    return new Response(`about ${groups.name}`);
  },
});

The problem is that when I type groups. it doesn’t suggest name as an autocomplete option.

Here is my route module:

type Route = {
  pathname: string;
  handler: CallableFunction;
};

const routes: Route[] = [];

export type DynamicGroups <T> = {
  [key in keyof T]: string;
};

export const push = (route: Route) => {
  routes.push(route);
};

export const response = (req: Request) => {
  for (const route of routes) {
    const pattern = new URLPattern({
      pathname: route.pathname,
    });

    const result = pattern.exec(req.url);

    if (result) {
      const groups: DynamicGroups = result.pathname.groups;

      return route.handler(groups);
    }
  }

  return null;
};

In my server code, I call the response function:

const server = Bun.serve({
  port: 3000,
  async fetch(req) {
    const routeResponse = route.response(req);

    if (routeResponse) {
      return routeResponse;
    }

    return new Response("404", {
      status: 404,
    });
  },
});

Based on the pathname of a route, I want autocompletion in vscode for each key.

This part of the code doesn’t work at all:

      const groups: DynamicGroups = result.pathname.groups;

      return route.handler(groups);

Is this even possible? Can I create a dynamic type based on the values of another type?

webserver making an API request to another server securly

I’ve been using C++ and python for years, but I’m a noob when it comes to web development.
I’m making a webpage that has content, select boxes and buttons.
The web server will make REST API requests to another server that I own that has the webapp/API running, and that as a response for a user clicking a button on the webpage.
All is going well, I have no problem with that, I’m using CORS , TLS , OAuth 2.0 etc… but … I can’t publish the webpage with the thought I have in mind about a risk/vulnerability, here it is…

I’m not expert by any mean, but I think that embedding the javascript or php code (that will make the API request) in the HTML is a bad idea and is a security risk that may reveal sensitive information to the client.

Any client can inspect the whole page with a simple F12 button, and see the source code.

So… how to secure/obfuscate this functionality? Is there another way better than embedding it in the HTLM code?

Thanks a lot.

Run python and get result as string in browser

I want to run Python code from a text-area in HTML and save the output in a div. I am using pyodide.js https://cdn.jsdelivr.net/pyodide/v0.25.0/full/pyodide.js to run Python. I would also like to use a worker which does not affect the main JS thread.

I have a working code that logs the output to the JavaScript console in the browser, and I can’t figure out a way to get the result in a string.

Can you help me get the code output saved to a variable?

The main function runPythonCode outputs the result to the console instead of returning an output to the variable result (result=undefined) in main-worker.js.

Find the detailed code below.

//test-code
import { runPythonCode } from "./main-worker.js";

$(element).find(".run-code:first").click(
     async function() {
          let current_code = "print('Hello, World!')"
                        
          let result = await runPythonCode(current_code)

          console.log("Run clicked", result)
       }
   )

// main-worker.js

// main-worker.js

import { asyncRun } from "./py-worker.js";

console.log("Python main worker started.")

async function runPythonCode(pythonCode, context) {
    try {
        const { result, error } = await asyncRun(pythonCode, context);
        if (result) {
            return result.toString()
        } else if (error) {
            return error
        }
    } catch (e) {
        console.error("Error communicating with the worker:", e);
    }
}

export {runPythonCode}

// py-worker.js

// py-worker.js

const pyodideWorker = new Worker("./worker.js");

const callbacks = {};

pyodideWorker.onmessage = (event) => {
    const { id, result, error } = event.data;
    const onSuccess = callbacks[id];
    delete callbacks[id];

    if (onSuccess) {
        if (result) {
            onSuccess({ result });
        } else if (error) {
            onSuccess({ error });
        }
    }
};

const asyncRun = (pythonCode, context = {}) => {
    const id = Date.now().toString(); // Unique identifier for each run
    return new Promise((resolve) => {
        callbacks[id] = resolve;
        pyodideWorker.postMessage({ id, pythonCode, context });
    });
};

export { asyncRun };

// worker.js

// worker.js

importScripts("https://cdn.jsdelivr.net/pyodide/v0.25.0/full/pyodide.js");

async function loadPyodideAndPackages() {
    self.pyodide = await loadPyodide({
        "indexURL" : "https://cdn.jsdelivr.net/pyodide/v0.25.0/full/",
    });
    // Add any necessary packages here
    // await self.pyodide.loadPackage(["numpy"]);
}

let pyodideReadyPromise = loadPyodideAndPackages();

self.onmessage = async (event) => {
    await pyodideReadyPromise;
    const { id, pythonCode, context } = event.data;

    // Copy the context variables to the worker's scope
    for (const key in context) {
        self[key] = context[key];
    }

    try {
        // Load packages and run Python code
        await self.pyodide.runPythonAsync(pythonCode);
        postMessage({ id, result: "Execution complete" });
    } catch (error) {
        postMessage({ id, error: error.message });
    }
};

Tried to invoke a web translator in headless-browser

How to solve this so confusing headless browser problem to invoke google translator in CLI, the javascript
if evaluated without check element’s text node it gave nothing
if checked with:

let i=0;
(function waitLo(e) {
  txt = e.textContent.trim();
  if ( ! txt && i++ < 5) {
    setTimeout( waitLo(e), 500)
  } else return txt
})();

logically to find why it gave nothing, it error as at bottom

const pup = require('puppeteer');

async function ggtranslate(string, tl='en') {
  const chrom = await pup.launch({headless:'new'});
  const page = await chrom.newPage();
  await page.goto(`https://translate.google.com/?sl=auto&tl=$(tl)&&op=translate`);
  // Find the input field and fill it
  const inputField = await page.waitForSelector(
  '#yDmH0d > c-wiz > div > div > c-wiz > div > c-wiz > div > div > div > c-wiz > span > span > div > textarea + div');
  await inputField.type(string);

  const translationE = await page.waitForSelector(
  '#yDmH0d > c-wiz > div > div.ToWKne > c-wiz > div.OlSOob > c-wiz > div.ccvoYb > div.AxqVh > div.OPPzxe > c-wiz > div.QcsUad > div > div > div > span > span > span');

  const result = await page.evaluate( e => {
    let i=0;
    (function waitLo(e) {
      txt = e.textContent.trim();
      if ( ! txt && i++ < 5) {
        setTimeout( waitLo(e), 500)
      } else return txt
    })();
    }, translationE);

  await chrom.close();
  return result;
}

console.log( ggtranslate(process.argv[2]));
console.log( process.argv[2]);

On terminal

$ node g.js bonjour
Promise { <pending> }
bonjour
node:internal/process/promises:289
            triggerUncaughtException(err, true /* fromPromise */);
            ^

Error [TypeError]: Cannot read properties of undefined (reading 'textContent')
    at waitLo (evaluate at ggtranslate (/tmp/opera/g.js:15:29), <anonymous>:3:14)
    at evaluate (evaluate at ggtranslate (/tmp/opera/g.js:15:29), <anonymous>:7:6)
    at #evaluate (/home/budi/.npm/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/ExecutionContext.js:221:55)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async ExecutionContext.evaluate (/home/budi/.npm/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/ExecutionContext.js:116:16)
    at async IsolatedWorld.evaluate (/home/budi/.npm/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/IsolatedWorld.js:123:16)
    at async CdpFrame.evaluate (/home/budi/.npm/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Frame.js:353:20)
    at async CdpPage.evaluate (/home/budi/.npm/node_modules/puppeteer-core/lib/cjs/puppeteer/api/Page.js:741:20)
    at async ggtranslate (/tmp/opera/g.js:15:18

Any one really expert in web development sincerely help out please

Issue with Hidden Div Not Displaying After Reloading [duplicate]

I have a simple AJAX function for updating some fields, and after that, I need to reload my div to display the new information. These divs are always initially set to “hidden,” so after the update, I need to show them again. However, it is not functioning as expected.

<div class="itemG hidden><div>

and ajax function is:

        function UpdatePhotoInformation(PhotoId) {
        pageWaitMe("progress"); // loading process starts
        $.ajax({
            contentType: 'application/x-www-form-urlencoded',
            postType: 'json',
            type: 'POST',
            data: { 'Id': PhotoId},
            url: 'myAction',
            success: function (data) {
                // something ...                 
            }
        }).always(function () {    
            $("#containerPhotos").load(window.location + " #containerPhotos");            
        }).ajaxStop(function () {
            $('.itemG').prop('hidden', false);
        });
    }

I tried using the following code in all AJAX events, such as “always,” “done,” “ajaxComplete,” and even “ajaxStop,” but none of them worked!

$('.itemG').prop('hidden', false);

I think there is an asynchronous problem with:

$("#containerPhotos").load(window.location + " #containerPhotos");   

and

$('.itemG').prop('hidden', false);

Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string

This is my .js file:

import express from "express";
import bodyParser from "body-parser";
import mongoose from "mongoose";
import cors from "cors";
import dotenv from "dotenv";
import multer from "multer";
import helmet from "helmet";
import morgan from "morgan";
// Below comes with node so we didn't install it.
import path from "path";  
import { fileURLToPath } from "url"; 
// These Two are used to setup paths when we are using directories. 


/*CONFIGURATIONS
These will include middleware config as well as package config*/
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
dotenv.config();
const app = express();
app.use(express.json())
app.use(helmet());
app.use(helmet.crossOriginResourcePolicy({policy:"cross-origin"}));
app.use(morgan("common"));
app.use(bodyParser.json({limit: "30mb", extended : true}));
app.use(bodyParser.urlencoded({limit:"30mb", extended:true}));
app.use(cors()) //Cross Orign Resource Policies. 
app.use("/assets", express.static(path.join(__dirname, 'public/assets')));
//The above line does is it sets dir where we keep our assets. In our cse we do it locally. In actual case we do it in a proper storage system 

/*FILE STORAGE */
const storage = multer.diskStorage({
    destination : function(req, file, cb){      
        cb(null, "public/assests");
    },
    //When someone uploads a photo into the wpage, it's gonna save in the public/assets folder. 
    filename : function(req, file, cb ){
        cb(null, file.originalname);
    }
})
const upload = multer({storage});
//This will help us save the img. Anytime we are going to upload a file we use the variable upload. 

//Go to mongoDB website and create a datbase cluster. 
//.env file is created. 

/*MONGOOSE SETUP */


const PORT = process.env.PORT || 6001;
mongoose.connect(process.env.MONGO_URL, {
    useNewUrlParser : true,
    useUnifiedTopology : true,
}).then(() => {
    app.listen(PORT, () => console.log(`Server Port : ${PORT}`));
}).catch((error) => console.log( `${error} did not connect`))

This is my .env file:

MONGO_URL = 'mongodb+srv://username:[email protected]/?retryWrites=true&w=majority'
PORT = 3001

Error i am facing is :
MongooseError: The uri parameter to openUri() must be a string, got “undefined”. Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string. did not connect

Plz help me.

I want the output to print the port number.

convert base64 to json in javaScript

For example, I have a base64 code like this

const base64 = "H4sIAAAAAAAEAO2b0W6CMBSGz6MsXm+JUKi6N9gzLLsw4jYTo0bJbpa9+44Ig0J7kBW0PSENNG2B9vtjw09PfYVvmMAGEjw/QwiPmKdYTmEL66xuAics7eGI5QcI4AmPSXbdAZZZ7Q7bX/InBFlLeYdaf37mFx7bSl2C5ROs8OoNPvHc9x6feOk5BAFR3tsK65O/MQmQEGP+g21VAgFzI8O5hx183Gz0zT5VBrW9SbLwkiTQsEQw9ZQl1NKY54nrNJf51CQS7IgidkQxOyLJjmjGjsjP9ylF5Ot71UQUe/x2NREFzIgkO88g2XkGyc4zSHaeQXrqGUTOVD3r+Xx0ECpXF1rKXaj382OnfMi92dX+h1ViZvAvByUtG+lYS+ta2ikpraX7qLnEcgLveX4530Jhyk+V95cjK/N7//76UEylovXTqUd5t1G9NvUonziq16Ye5UlH9drUo/zvqF6bepTXHtWj1Ztf6W3/q16x6nOdfqGH+l3nj0f9TPoNO3sj9vpRX+Kjfu36Detcivg4X/2G9S789Rv2q63YacJXv2G/27jrZ1avupcqJBQKe9WnWBtqcoss8qGPw9lErfodf1+RRZuolZtENlErN4lsolZuEtlErdwksolTuUlks9PFTSKbnS4uEkmrnS5uEtnsdHGRaE4S2fvG/pldco2LgVe9RAf1xA3UW8Entm6zUdS1CHC26+e7mW/R6as2aiXUjVk/UupXH2f7KNvXw6ed1oRi6xkd5f+heINfmSW/7QgyAAA="

Now I want to convert this to json

How to correctly close a webRTC connection, so that it can be removed from chrome://webrtc-internals

I have a Video Calling application built using webRTC. When a user disconnects a call, the call ends smoothly, even the connectionstatechange becomes closed which is fine. On closing the call I am running this function

async closeConnection() { if (!this.peer) return; if (this.peer?.onicecandidate) this.peer.removeEventListener("icecandidate", this.peer.onicecandidate); if (this?.peer?.ontrack) this.peer.removeEventListener("track", this.peer.ontrack); if (this?.peer?.onnegotiationneeded) this.peer.removeEventListener("negotiationneeded", this.peer.onnegotiationneeded); this.peer.close(); console.log('closing the peer connection....') }

But the info is still visible in chrome://webrtc-internals and sometimes it happens that browser freezes and shows Out of Memory which means there may be a memory leak.

closed state in chrome://webrtc-intrernals

Could someone please suggest me what can be done to resolve this issue?

After closing the webRTC connection it should also removed from chrome://webrtc-internals browser should free up all the resources were used during the connection.

Configure facebook login button for Business not allowed to add config_id

I have created a Facebook Business web app in a react project and want to add config_id while logging in. As the documentation mentioned for the business web app, https://developers.facebook.com/docs/facebook-login/facebook-login-for-business, we can add config_id in FB.login() and on a click of HTML button, we can do the login.

But I don’t want use the HTML button and want to use Facebook Login Button which is documented here. https://developers.facebook.com/docs/facebook-login/web/login-button, I am using following thing to add the Facebook button,

<div 
  className="fb-login-button"
  data-max-rows="1"
  data-size="large"
  data-button-type="login_with"
  data-layout=""
  data-use-continue-as="true"
></div>

But I could not find a way to add config_id here and I am kind of stuck here for using Facebook login button for Facebook business app. Is there a way to add the config_id here?

When to use object over hashmap

https://leetcode.com/problems/roman-to-integer/solutions/4127892/beats-99-99-easy-solution-with-o-n-approach-c-python-java-javascript/

I was looking at this solution on Leetcode which uses a “hashmap”. I did some research and found there is no official hashmap in javascript but there is a map and an object which differ. I’m still learning the difference between the two.

My question is why was an object used for this example? Is that the correct way of doing it or would it be more professional to use a map?

I thought this would be incorrect because an object is used for storing personalized data but here we’re using it like a map.