React putting props as variables in javascript template literals

I’m trying to pass a react props into a javascript template literal:

function Yuh(props) {
    return <a href={`javascript:console.log(${props.i})`}>{props.i} <h2>a</h2></a>
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Yuh i='lmao' />);

But I’m getting this error:
Uncaught ReferenceError: lmao is not defined

I tried to replace i='lmao' with i={5} and that seems to work. How do I make it so that strings also work?

Thanks!

Three.js on website not appearing on GitHub pages, but working fine on localhost? How to fix?

I finished my first three.js project, and it runs fine and works on my local device (it’s just a page of a black background and a ball that changed colour when you spin it).

However, when I uploaded it to GitHub to try and host it on GitHub pages it didn’t render the Three.js animations and instead replaced the whole scene with a white background.

I tried changing the source of the stylesheets and scripts, varying from “/styles.css” to “./styles” to even “url.com/repo/myproject/styles.css” but nothing seemed to work.

If you’d like to look at my code, here is the public repositiory.

How to rerender a component from a stack navigator

For those of you familiar with React-Native, how do I re-render a component from inside of another screen that was navigated to through stack navigator. Excuse the horrible code I’m a sophomore in highschool, this is my first app.

  • Each book passes its contents to the VocabList screen when clicked using stack navigator
    -State of books is being tracked here
<View style={styles.listContainer}>
    <View>
        <FlatList
            data={bookArray}
            renderItem={({ item }) => (
                <Book
                    wordCountProp={item.wordCount[0]}
                    key={item.id}
                    uuid={item.id}
                    title={item.text}
                    list={item.definitionArray}
                    changeModalVisible={changeModalVisible}
                    contrivedRender={contrivedRender}
                    handleDeleteComponent={(uuid) => handleDeleteBook(uuid)}
                    handleFavoriteBook={(uuid) => handleFavoriteBook(uuid)}
                    handleUnFavoriteBook={(uuid) => handleUnFavoriteBook(uuid)}
                    navigateStackHandler={(
                        id,
                        definitionArrayParam,
                        setDefinitionArray
                    ) =>
                        props.navigation.navigate(
                            "VocabList",
                            item,
                            id,
                            definitionArrayParam,
                            setDefinitionArray
                        )
                    }
                />
            )}
        />
    </View>
</View>
  • This is how data is read from the book and displayed on the screen depending on which book you click
  • State of definitions isn’t being tracked on this screen, rather by each independent book component
<View style={styles.listContainer}>
    <FlatList
        data={props.navigation.getParam("definitionArray")}
        renderItem={({ item }) => (
            <Definition
                key={item.id}
                uuid={item.id}
                title={item.text}
                handleDeleteComponent={(id) => {
                    props.navigation
                           .getParam("definitionArray")
                           .splice(
                               props.navigation
                                   .getParam("definitionArray")
                                   .indexOf(
                                       props.navigation
                                       .getParam("definitionArray")
                                       .filter((definition)=>definition.id === id)[0]
                                ),
                            1
                        );
                    if (props.navigation.getParam("wordCount")[0] > 0)
                        props.navigation.getParam("wordCount")[0] -= 1;
                }}
                navigateStackHandler={(id, definitionArra) =>
                    props.navigation.navigate("VocabList", item, id, definitionArra)
                }
            />
        )}
    />
</View>

What can I do to force the book to rerender as soon as it is updated with a new vocabulary word, or a word is deleted?

I tried keeping track of definition state inside of the VocabList screen but then again I can’t communicate with the book component because the contents of the book were simply passed as parameters to the VocabList screen using stack navigator. The VocabList screen doesn’t even know the book exists.

Chrome extension – Manifest_version: 3

I made a simple Chrome extension some time ago. It replaces some words, one for the other. It worked until it changed the “manifest_version”: 2 to 3. An example of an error is the inability to access the YouTube.com.
Here’s the code for the manifest.json:

{
    "manifest_version": 3,
    "name": "Change words",
    "version": "1.0",
    "content_scripts": [
      {
        "matches": ["<all_urls>"],
        "js": ["content.js"]
      }
    ]
}

Code for content.js:

document.body.innerHTML = document.body.innerHTML.replace(/word01/g, "word02");
document.body.innerHTML = document.body.innerHTML.replace(/word03/g, "word04");
document.body.innerHTML = document.body.innerHTML.replace(/word05/g, "word06");

Thank you everyone.


I tried to run a Chrome extension that replaces some words with others, but it stopped working after changing the “manifest_version 2” to “manifest_version 3”. I expected the extension to work as before, but it resulted in an error, specifically the inability to access the YouTube site.

passport always takes me to failureRedirect

I am creating a login and user registration with Node.js.

the problem is that passport always takes me to failureRedirect and i dont know why

'use strict';

const express = require('express');
const User = require('../../models/User');
const { Router } = require('express');
const router = express.Router();
const passport = require('passport')


router.get('/', (req, res, next) => {
  res.render('index');
});


// GET /signup
router.get('/signup', (req, res, next) => {
  res.render('signup');
})


// POST /signup    
router.post('/signup', passport.authenticate('local-signup', {
  successRedirect: '/',
  failureRedirect: '/signup',
  passReqToCallback: true
})) 

// GET /login
router.get('/login', (req, res, next) => {
  res.render('login');
});

// POST /login
router.post('/login', passport.authenticate('local-login', {
  successRedirect: '/',
  failureRedirect: '/login', 
  passReqToCallback: true
}));


  module.exports = router;

This my app.js file

var createError = require('http-errors');
var express = require('express');
var cors = require('cors');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const passport = require('passport')
const session = require('express-session')
const flash = require('connect-flash')

// connection to the DB
require('./lib/connectMongoose');

// require passport
require('./passport/local-auth')

// connection to API
const usersApi = require('./routes/api/users')
const postsRouter = require('./routes/api/posts')
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(cors());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
  secret: 'mysecretsession',
  resave: false,
  saveUninitialized: false
}))

app.use(flash())
app.use(passport.initialize())
app.use(passport.session())
app.use((req, res, next)=> {
  app.locals.registerMessage = req.flash('signupMessage')
  app.locals.loginMessage = req.flash('loginMessage')
  next();
});

// API routes

app.use('/api/posts', postsRouter);

app.use('/api/users', usersApi);
app.use('/', require ('./routes/api/login'));

app.use('/', indexRouter);
app.use('/users', usersRouter);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

This is my passport file:

const passport = require('passport');
const localStrategy = require('passport-local').Strategy;
const User = require('../models/User')

//serialize user to save signup
passport.serializeUser((user, done) => {
    done(null, user.id)
});

//authenticate the id in the browser
passport.deserializeUser( async(id, done) => {
    const user = await User.findById(id)
    done(null, user)
});


// receive registration and validate it
passport.use('local-signup', new localStrategy({
    usernameField: 'username',
    emailField: 'email',
    passwordField: 'password',
    passReqToCallback: true
} , async (req, email, username, password, done) => {

    const user = await User.findOne({ email: email }, { username: username})
    if (user) {
        return done(null, false, req.flash('signupMessage', 'The email or username is already taken'))
    } else {
        const newUser = newUser();
        newUser.username = username;
        newUser.email = email;
        newUser.password = newUser.encryptPassword(password); 
        console.log(newUser)
        await newUser.save();
        done(null, newUser);
    }
}))




passport.use('local-login', new localStrategy({
    usernameField: 'email',
    passwordField: 'password',
    passReqToCallback: true
  }, async (req, email, password, done) => {
    const user = await User.findOne({email: email});
    if(!user) {
      return done(null, false, req.flash('loginMessage', 'No User Found'));
    }
    if(!user.comparePassword(password)) {
      return done(null, false, req.flash('loginMessage', 'Incorrect Password'));
    }
    return done(null, user);
  }));

What I need is that when doing the login it takes me to the home page of the application. Apparently I have some error and that’s why it takes me to the login page again but I don’t get the error….

Python plot window not closing after being called from a JavaScript script

I have a JavaScript script (open_hist_w_user.js) spawns a python process and passes data to a python script (create_histogram.py). The Python script creates a histogram using the Matplotlib library and displays it. The problem is that even after calling plt.close(‘all’), the plot window does not close.

Code:

*javascript; open_hisr_w_user.js*
/**
 * This script is used to spawn a python process that generates a histogram for the specified username.
 * 
 * @param {string} username - The username for which the histogram is being generated.
 * 
 * @returns {ChildProcess} - The spawned python process.
 */

const { spawn } = require('child_process');
const username = 'some_username';
const pythonProcess = spawn('python', ['./create_histogram.py', username]);


python;create_histogram.py
import matplotlib.pyplot as plt
import sys
import time

def create_histogram(username):
    """
    This function creates a histogram of data, with a specified number of bins and range, and displays it.

    Parameters
    ----------
    username : str
        The username for which the histogram is being generated.

    Returns
    -------
    None
    """
    plt.close('all')  # close any previous plot windows

    # plot the histogram
    plt.clf()  # clear the previous plot
    plt.hist([1, 2, 3, 4, 5], bins=3, range=(0, 5))
    plt.xlabel('Total')
    plt.ylabel('Frequency')
    plt.title(f'Histogram of Total Column for {username}')
    plt.show()  # show the plot
    time.sleep(5)  # wait for 5 seconds
    plt.close('all')  # close the plot window
if __name__ == "__main__":
    username = sys.argv[1]
    create_histogram(username)

I tried using plt.close(‘all’) to close the plot window, but it did not work. I expected the plot window to close after some delay after the histogram was created. Before you ask why am I not just using a javascript script,I tried porting my code a few days ago using plotly and df3, but couldn’t get it working; so here we are passing data through the console.
Expected Result:
insert image of closed window here

Actual Result:
image of an unclosed plot

i can not use attributes while using ejs. “.name” part is not working

I am trying to export datas from mongodb and even i add the attribute of my data, i can not receive what i want. I am just a rookie and i couldn’t find the solution on web

<%newListItems.forEach(function(item){ %>
    
        <div class="item">
            <input type="checkbox">
               <p> <%= item.name %> </p>
        </div>
        <% })  %> 

this is my code and “.name” part is not working. how can i figure it out? thanks.

(js) e.target takes different things when the same target (a button) is clicked more than once

I have a To-Do list with an input, button that adds elements and div where the tasks are saved. No database, just JS, so it when it refreshes, the list becomes empty again.

Here is the code. The problem is with the delete button. I create one for each tasks but it doesn’t works right. It sometimes delete only the element, but other times deletes the div with all of the tasks.

This is the line of code that gives me the error: deleteBtn.onclick = (e) => e.target.parentElement.parentElement.remove(). The problem is not with the parent element, I’ve tried to fix it without the double use of it and that can only delete the button or the element of the list – again different results from one single button.

So, what I saw is that console.log(e.target) gives me different things when I click the delete button.

  • It sometimes takes only the <i class="fa-solid fa-trash-can"></i>.
  • And other times it takes the whole button: <button class="deleteTask"> <i ...></i> </button>.

So, can somebody tell me why e.target is not taking the same thing when I do click on the same button everytime

Is it possible to retrieve all imported objects in ES6 modules?

With RequireJS, you can do something like:

define(['a', 'b', 'c'], function(a, b, c) { 
    console.log(arguments);
}

Is it possible to do something similar for an ES6 module? Ex:

import a from 'a.js';
import b from 'b.js';
import c from 'c.js';

console.log(imported_objects); // should console log the values of a, b, and c

I’m asking because I’m working on a project that transforms AMD code to ES6 modules. When I do the transform, arguments is undefined because we’re no longer inside of a function, but I need to be able to do something similar in ES6. I’m guessing this isn’t possible because these are static imports? Thanks for any help

How to invoke IIFE function from external file in useEffect?

I was able to run scoper.js function by using script tag <script src="...">. Now I took that scoper.js function out of src and placed them in different file then try to invoke that function in App.js by importing it. But I’m having no luck. I tried window.onload and even setTimeout, but nothing works. My only guess is scoper.js is called immediately by IIFE so needs to be invoked differently if not invoking it by script tag? Please help.(If called successfully, “Hello World” should be in red color.)https://codesandbox.io/s/stylesheet-scoping-b0k9pp?file=/src/App.js

App.js

import React, { useEffect } from "react";
import "./styles.css";
import { scoper } from "./scoper.js";

export default function App() {
  useEffect(() => {
    const script = document.createElement("script");

    script.src =
      "https://cdn.rawgit.com/thomaspark/scoper/5de04619/scoper.min.js";
    script.async = true;
    // document.body.appendChild(script); // this method works
    window.onload = function () {
      scoper(); // this not working
    };

    let style = document.createElement("style");
    style.setAttribute("scoped", "");
    style.innerHTML =
      ".Puma {" +
      "color: purple;" +
      "font-size: 50px;" +
      "text-align: left;" +
      "}";
    let main = document.getElementById("raptors");
    main.appendChild(style);

  }, []);

  return (
    <>
      <div id="lakers" className="Puma">
        <div>Hello World!</div>
      </div>
      <div id="raptors" className="Puma">
        <h1>Raptors win!</h1>
      </div>
    </>
  );
}

scoper.js

function scoperInit() {
  var style = document.createElement("style");
  style.appendChild(document.createTextNode(""));
  document.head.appendChild(style);
  style.sheet.insertRule("body { visibility: hidden; }", 0);
}

function scoper(css, prefix) {
  console.log("css is ", css);
  console.log("prefix is ", prefix);
  var re = new RegExp("([^rn,{}]+)(,(?=[^}]*{)|s*{)", "g");
  css = css.replace(re, function (g0, g1, g2) {
    if (
      g1.match(/^s*(@media|@.*keyframes|to|from|@font-face|1?[0-9]?[0-9])/)
    ) {
      return g1 + g2;
    }

    if (g1.match(/:scope/)) {
      g1 = g1.replace(/([^s]*):scope/, function (h0, h1) {
        if (h1 === "") {
          return "> *";
        } else {
          return "> " + h1;
        }
      });
    }

    g1 = g1.replace(/^(s*)/, "$1" + prefix + " ");

    return g1 + g2;
  });

  return css;
}

function scoperProcess() {
  var styles = document.body.querySelectorAll("style[scoped]");

  if (styles.length === 0) {
    document.getElementsByTagName("body")[0].style.visibility = "visible";
    return;
  }

  var head = document.head || document.getElementsByTagName("head")[0];

  for (var i = 0; i < styles.length; i++) {
    var style = styles[i];
    var css = style.innerHTML;

    if (css && style.parentElement.nodeName !== "BODY") {
      var id = "scoper-" + i;
      var prefix = "#" + id;

      var wrapper = document.createElement("span");
      wrapper.id = id;

      var parent = style.parentNode;
      var grandparent = parent.parentNode;

      grandparent.replaceChild(wrapper, parent);
      wrapper.appendChild(parent);
      style.parentNode.removeChild(style);

      var newstyle = document.createElement("style");
      newstyle.setAttribute("data-scoped-style-for", id);
      var csses = scoper(css, prefix);
      if (newstyle.styleSheet) {
        newstyle.styleSheet.cssText = csses;
      } else {
        newstyle.appendChild(document.createTextNode(csses));
      }

      head.appendChild(newstyle);
    }
  }

  document.getElementsByTagName("body")[0].style.visibility = "visible";
}

function scoperReset() {
  var styles = document.head.querySelectorAll("style[data-scoped-style-for]");
  for (var i = 0; i < styles.length; i++) {
    var style = styles[i];
    var wrapperElementId = style.getAttribute("data-scoped-style-for");
    var wrapperEl = document.getElementById(wrapperElementId);
    if (wrapperEl) {
      // Node may have disappeared, in that case nothing should happen
      var css = style.innerHTML;
      var resettedCss = css.replace("#" + wrapperElementId + " ", "");

      var parent = wrapperEl.parentNode;
      var targetEl = wrapperEl.childNodes[0];

      parent.replaceChild(targetEl, wrapperEl);
      var scopedStyle = document.createElement("style");
      scopedStyle.setAttribute("scoped", "true");
      if (scopedStyle.styleSheet) {
        scopedStyle.styleSheet.cssText = resettedCss;
      } else {
        scopedStyle.appendChild(document.createTextNode(resettedCss));
      }
      targetEl.appendChild(scopedStyle);
    }

    style.parentNode.removeChild(style);
  }
}

function scoperRestart() {
  scoperReset();
  scoperProcess();
}

(function () {
  "use strict";

  if (
    typeof document === "undefined" ||
    "scoped" in document.createElement("style")
  ) {
    return;
  }

  scoperInit();

  if (document.readyState === "complete" || document.readyState === "loaded") {
    scoperProcess();
  } else {
    document.addEventListener("DOMContentLoaded", scoperProcess);
  }
})();

if (typeof exports !== "undefined") {
  exports.scoper = scoper;
}

Chrome Extension : chrome.tabs.executeScript doesn’t work

I am building a chrome extension that opens a search bar upon pressing a hotkey and when enter is pressed it shows dummy results.

I have defined the following files

background.js

chrome.commands.onCommand.addListener((command) => {
    if(command === "launch") {
        chrome.tabs.executeScript({
            file: "insertSearchBar.js"
        });
    }
});

This file launches insertSearchBar.js correctly.

insertSearchBar.js

var div=document.createElement("div");
var innerDiv=document.createElement("input");
...
div.addEventListener('keypress', function(e) {
    if(e.key == "Enter") {
        chrome.tabs.executeScript({
            file: "insertSearchResultView.js"
        });
    }
})

This file doesn’t execute chrome.tabs.executeScript correctly and doesn’t launch a new view on the current tab.

insertSearchResultView.js

var div=document.createElement("div");
document.body.appendChild(div);
var innerDiv=document.createElement("input");
div.appendChild(innerDiv);

Ways to capture r shiny Handsontable in a jspdf printout without corruption

I’ve been working of a reporting feature for an app. It has several small tables that I have been copying over with dom-to-image in jsPDF.

var image = new Image();
  var node;
node = document.getElementById("Table1");
    await domtoimage.toPng(node)
    .then(function (DataURL){
      doc.addImage(DataURL, "PNG", 23, 123, node.clientWidth/4.875, node.clientHeight/4.875);
    });

Recently the images that the tables are have been showing up corrupted with sections edited out. Is there a handsontable js call like in plotly to copy over the table as a data URL?

image = await Plotly.toImage("graph1");
    doc.addImage(image, "JPEG", 12.5, 22.5, 180, 100);

Or an easier way to prevent the images from being corrupted?
I was recently using html2canvas but the speed and memory usage would crash Chrome and Firefox whenever I would generate a report.

I have changed around the image type dom-to-image pulls, from PNG to JPEG, and Blob as well. I have edited my CSS file to remove any chance these charts and tables would overlat in the app interface as another safety measure as well.

How can I turn this const time conversion formula into a reusable function? [duplicate]

I’ve been trying to turn the following simple millisecond to “minutes and seconds” conversion into a function. I’d like to use a function so I can easily send the milliseconds as a parameter and then return the formatted minutes and seconds.

const date = new Date(123456);
`${date.getMinutes()} minutes ${date.getSeconds()} seconds`; // Expected result: "2 minutes 3 seconds"

For the life of me I can’t figure it out. I’m both seeking a short term solution and also an reason this isn’t as simple as it seems, as I’m still very new to learning JavaScript.