How to change CSS of an exetrnal website in Electron?

I’m trying to create a simple web wrapper for a messaging website as practice, and I’ve created this simple code to load that website into Electron. Now I want to change this site’s CSS properties. Multiple sources, including the docs seem to imply that using .webContents.insertCSS is the easiest way to do this. But whenever I run my program, this doesn’t work.

Here is the code that I have been working with:

const {app, BrowserWindow, webContents} = require('electron');
const fs = require('fs'); 

const createWindow = () => {
  let win = new BrowserWindow({
    width: 800,
    height: 600
  })

  win.loadURL('https://messenger.com/login'); 

  win.webContents.insertCSS(`.rq0escxv.l9j0dhe7.du4w35lb.j83agx80.cbu4d94t.g5gj957u.d2edcug0.hpfvmrgz.kud993qy.buofh1pr {
    margin-top: unset !important;
    }
    
    /* Scrollbar fixes. */
    ::-webkit-scrollbar {
    width: 0px !important;
    overflow-x: hidden;
    }
        
    :root, .__fb-light-mode, .__fb-dark-mode{
        --messenger-card-background: #262626 !important;
        --surface-background: #353535 !important;
        --hosted-view-selected-state: #262626 !important;
    }
    
    .system-fonts--body{
      font-family: 'Geist Regular' !important;
    }
    
    .x1247r65{
        width: 0px !important;
        visibility: hidden !important;
    }
    
    .x9f619.x1n2onr6.x1ja2u2z
    .x78zum5.xdt5ytf.x2lah0s
    .x193iq5w.xurb0ha.x1sxyh0
    .xdj266r{
        display: none !important;
    
    }
    
    .x1heor9g.x1qlqyl8.x1pd3egz.x1a2a7pz{
        margin-left: 0px !important;
    }
    
    .xm81vs4,.xy80clv{
        border-right-width: 0px !important;
        border-left-width: 0px !important;
    }
    `);

}

app.whenReady().then(() => {
  createWindow()
})

Thanks for the answer in advance!

“CORS Errors Persist Despite Using cors Middleware in Node.js and React App”

I’m struggling with CORS problems in my Node.js (localhost:3000) and React (localhost:8000) app. I’ve added cors middleware to my server, but CORS errors persist when making requests from React. Here’s a snippet:

const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());

// ... other middleware

app.listen(3000, () => console.log('Server running on port 3000'));








I M trying to resolve and expected it to be resolve ASAP

TypeError: Cannot read property ‘getValue’ of null at Object.onAction

Help please.
Im trying to pull the changes made on a customer record in Netsuite.
But Im getting this error: TypeError: Cannot read property ‘getValue’ of null [at Object.onAction.
Im doing an edit and save on Customer record but only newRecord is logged.
Can you help. TIA!

 /**
 * @NApiVersion 2.1
 * @NScriptType workflowactionscript
 */

define(["N/record", "N/runtime", "N/redirect"], function (
  record,
  runtime,
  redirect
) {
  let GLOBALVAR = {
    CUSTOMER: {
      RECORD: "customer",
      ID: "internalid",
      STATUS: "custentity_custstatus",
      INACTIVE: "inactive",
    },
    CUSTOMER_FIELDS: [
      "id",
      "isperson",
      "companyname",
      "entitystatus",
      "salesrep",
      "partner",
      "url",
      "category",
      "comments",
      "email",
      "phone",
      "defaultaddress"
    ],
  };

  function onAction(scriptContext) {
    log.debug("onAction", "onAction");
    let objScript = runtime.getCurrentScript();

    if (scriptContext.type == "edit") {
      let oldRec = scriptContext.oldRecord;
      let newRec = scriptContext.newRecord;
      let customerfields_updated = false;

      for (let i = 0; i < GLOBALVAR.CUSTOMER_FIELDS.length; i++) {
        let newValue = newRec.getValue({ fieldId: GLOBALVAR.CUSTOMER_FIELDS[i] });
        let oldValue = oldRec.getValue({ fieldId: GLOBALVAR.CUSTOMER_FIELDS[i] });

        if (oldValue != newValue) {
          customerfields_updated = true;
          record.submitFields({
            type: GLOBALVAR.CUSTOMER.RECORD,
            id: newRec.id,
            values: {
              'isinactive': true,
            },
          });
          
          log.debug("customerfields_updated", customerfields_updated);
        }
      }
      log.debug('_Remaining governance units: ' , objScript.getRemainingUsage());
    }
  }

  return {
    onAction: onAction,
  };
});

Why one of the “ifs” is working when the other one is not. They are in the same function [closed]

let pytanko;
let odpowiedz;

const LoadData = async () => {
  const url = "https://marcconrad.com/uob/tomato/api.php";

  const res = await fetch(url);
  const data = await res.json();
  pytanko = data.question;
  odpowiedz = data.solution;
  return data;
};

LoadData().then(() => {
  document.getElementById("tomatoimg").setAttribute("src", pytanko);
  console.log("the answer should be: ", odpowiedz);

  const check = document.getElementById("checkbutton");
  check.addEventListener("click", () => {
    let getInput = document.getElementById("inputboxx").value;
    if (getInput === odpowiedz) {
      document.getElementById("testid").style.backgroundColor = "green";
      console.log("good answerrr");
    }
    if (getInput != odpowiedz) {
      document.getElementById("testid").style.backgroundColor = "red";
      console.log("wrong answerrr");
    }
  });
});

if getInput != odpowiedz is working fine, changes the background color and console logs out the error message. But why when answer is right nothing happens?

Both and “getInput” and “odpowiedz” are single digit numbers 0-9

How to Fix Incorrect Progress and Progress Percentage in the Upload Progress Bar

I have created a multifile loading application where you can load multiple files and one upload button. After clicking the button, all files are uploaded with progress and percentages. Here is the problem I am facing: when we are clicking the upload button, the process of progress and the increasing percentages are not proper, and after the upload is completed successfully, the percentage should stop, but it keeps counting 10-100 again. So how do I resolve that progress bar issue that the progress bar percentage-wise should fill, and after completion, it says upload successfully and without select if we upload then it will say file should select?

import { useState, useCallback, useEffect } from "react";
import Button from "@material-ui/core/Button";
import axios from "axios";
import AttachFileIcon from "@mui/icons-material/AttachFile";
import LinearProgress from "@mui/material/LinearProgress";

export default function App() {
  const [files, setFiles] = useState([]);
  const [msg, setMsg] = useState(null);
  const [progress, setProgress] = useState({ started: false, pc: 0 });
  const [progressNum, setProgressNum] = useState(10);
  useEffect(() => {
    const timer = setInterval(() => {
      if (progressNum <= 100) {
        setProgressNum((progressNum) =>
          progressNum >= 100 ? 10 : progressNum + 10
        );
      } else {
        return;
      }
    }, 800);
    return () => {
      clearInterval(timer);
    };
  }, []);
  const handleUpload = useCallback(() => {
    if (!files) {
      setMsg("no file selected");
      return;
    }
    const fd = new FormData();
    for (let i = 0; i < files.length; i++) {
      fd.append(`file${i + 1}`, files[i]);
    }
    setMsg("Uploading...");
    setProgress((prevState) => {
      return { ...prevState, started: true };
    });
    axios
      .post("http://httpbin.org/post", fd, {
        onUploadProgress: (progressEvent) => {
          setProgress((prevState) => {
            return { ...prevState, pc: progressEvent.progress * 100 };
          });
        },
        headers: {
          "Custom-Header": "value",
        },
      })
      .then((res) => {
        setMsg("Upload successfully");
        console.log(res.data);
      })
      .catch((err) => {
        setMsg("Upload Failed");
        console.log(err);
      });
  }, []);
  console.log(progress.pc < 100);
  const handleFileChange = (e) => {
    const selectedFiles = e.target.files;

    setFiles((prevFiles) => [...prevFiles, ...Array.from(selectedFiles)]);
  };

  return (
    <>
      <Button variant="contained" component="label">
        Upload File
        <input type="file" onChange={handleFileChange} hidden multiple />
      </Button>
      <Button
        onClick={handleUpload}
        variant="contained"
        color="primary"
        component="span"
      >
        Upload
      </Button>
      {Object.values(files).map((file) => {
        return (
          <div
            key={file.id}
            style={{
              width: "500px",
              padding: "8px",
              backgroundColor: "rgba(0,0,0,0.05)",
            }}
          >
            <AttachFileIcon />
            {file.name}
            <div>
              {progress.started && (
                <span>
                  <LinearProgress
                    variant="determinate"
                    value={progress.pc}
                    color={progress.pc < 100 ? "primary" : "success"}
                  />{" "}
                  {progressNum}
                </span>
              )}
            </div>
          </div>
        );
      })}
      {msg && <span>{msg}</span>}

    </>
  );
}

Signature pad is not sending the signature to google drive folder

I made an HTML, CSS, and JS (GS) program with Google App Scripts. The web app launches and the app works fine just the send button doesn’t send the picture of the signature drawn on the canvas to the Google Drive folder. The send button is supposed to convert the signature drawn into a PNG and send it to the linked Google Drive folder.

HTML:


<!doctype html>
<html lang="en">
  <head>
    
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <title>Signature Pad</title>
    <link rel= "stylesheet" href="style.css">
  </head>
 
 
  <body>
    <div id = "app" class = "container">
        <div class = "margin text-center">
        <div class = "canvas mx-auto"> 
          <h1> Important Contract </h1>
          <p> Description </p>
        <canvas id = "sig" width = "500px" height = "500px" class = "border"> </canvas>
        <div> 
            <button type="button" class="btn btn-dark" id = "clearSig">Clear</button>
            <button type="button" class="btn btn-dark" id ="send">Send</button>
        </div>
      </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/signature_pad.umd.min.js"></script>
    <script>

        var signaturePad;
          function setupSignatureBox(){
            var canvas = document.getElementById("sig");
            signaturePad = new SignaturePad(canvas);
          }

          function clearSignature(){
            signaturePad.clear();
          }

          function sendToDrive(){
            signaturePad.toDataURL();
            google.script.run.recieveSignature(imageData);
          }

          document.getElementById("clearSig").addEventListener("click",clearSignature);
          document.getElementById("send").addEventListener("click",sendToDrive);
          document.addEventListener("DOMContentLoaded",setupSignatureBox);
    </script>
  </body>
</html>

JS (GS) :

function doGet() {
  return HtmlService.createTemplateFromFile("index").evaluate();
}

function recieveSignature(encodedImage){
 
  const data = encodedImage.split(",")[1];
  const dataDecoded = Utilities.base64Decode(data);
  const signatureAsPictureBlob = Utilities.newBlob(dataDecoded).setName("somefile.png");
  DriveApp.getFolderById("1DlVK84J9gVjfk5Gepw9L2pOhfMCFk74Q").createFile(signatureAsPicture);

}

SwiperJS block my scroll animation on his element (the slider i create with swiperjs). Ho can i solve it?

HTML

<div class="clients-box clients-projects hidden-right">
          <!-- PROVA -->
          <div class="swiper mySwiper">
            <div class="swiper-wrapper">
              <div class="swiper-slide">
                <div class="swiper-custom-container">Slide 1</div>
              </div>
              <div class="swiper-slide">
                <div class="swiper-custom-container">Slide 2</div>
              </div>
              <div class="swiper-slide">
                <div class="swiper-custom-container">Slide 3</div>
              </div>
              <div class="swiper-slide">
                <div class="swiper-custom-container">Slide 4</div>
              </div>
              <div class="swiper-slide">
                <div class="swiper-custom-container">Slide 5</div>
              </div>
              <div class="swiper-slide">
                <div class="swiper-custom-container">Slide 6</div>
              </div>
              <div class="swiper-slide">
                <div class="swiper-custom-container">Slide 7</div>
              </div>
              <div class="swiper-slide">
                <div class="swiper-custom-container">Slide 8</div>
              </div>
              <div class="swiper-slide">
                <div class="swiper-custom-container">Slide 9</div>
              </div>
            </div>
            <div class="swiper-button-next"></div>
            <div class="swiper-button-prev"></div>
            <div class="swiper-pagination"></div>
          </div>
        </div>

CSS ANIMATION

.hidden-right {
  opacity: 0;
  filter: blur(3px);
  transform: translateX(100%);
  transition: all 1s ease;
}

.show-right {
  opacity: 1;
  filter: blur(0px);
  transform: translateX(0);
}

JS for SCROLL ANIMATION

const observerLeft = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    console.log(entry);
    if (entry.isIntersecting) {
      entry.target.classList.add("show-left");
    } else {
      entry.target.classList.remove("show-left");
    }
  });
});

const hiddenElementsLeft = document.querySelectorAll(".hidden-left");
hiddenElementsLeft.forEach((el) => observerLeft.observe(el));

const observerRight = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    console.log(entry);
    if (entry.isIntersecting) {
      entry.target.classList.add("show-right");
    } else {
      entry.target.classList.remove("show-right");
    }
  });
});

const hiddenElementsRight = document.querySelectorAll(".hidden-right");
hiddenElementsRight.forEach((el) => observerRight.observe(el));

const observerTop = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    console.log(entry);
    if (entry.isIntersecting) {
      entry.target.classList.add("show-top");
    } else {
      entry.target.classList.remove("show-top");
    }
  });
});

const hiddenElementsTop = document.querySelectorAll(".hidden-top");
hiddenElementsTop.forEach((el) => observerTop.observe(el));

all the elements that i provided them with the class=”hidden-right” actually work but, when i put it to the element with the class=”clients-projects” it works only during the page refresh, and after when i scroll it doesn’t work. it seems like it doesn’t has the class for animation. and i don’t know how to solve it.
Can someone help me pls?

What is wrong with this React Context?

I’m trying to get this to toggle the theme light and dark… the specifications require it to pass theme and toggleTheme. In the toggle component, onChange is set to toggleTheme. That part works, it’s just setting the state that seems to work for one toggle but not any subsequent toggles (or toggling back).

Disclaimer: This is for a course on Coursera. The lab is not a graded lab. The answer is locked until I complete the lab though and I don’t know what completing the lab means to achieve the requirements.

import { createContext, useContext, useState } from 'react';

const ThemeContext = createContext(undefined);

export const ThemeProvider = ({ children }) => {
    const toggleTheme = (e) => {
        if (theme["theme"] === "dark") {
            setT({"theme":"light", toggleTheme});
        } else {
            setT({"theme":"dark", toggleTheme});
        }
    }
    const [theme, setTheme] = useState({
        theme: "dark",
        toggleTheme: () => toggleTheme
    });
    return <ThemeContext.Provider value={theme}>{children}</ThemeContext.Provider>;
}

export const useTheme = () => useContext(ThemeContext);

I’ve tried passing the theme and toggleTheme in as parameters, but it said toggleTheme wasn’t a function. I’m expecting it to toggle the color scheme to go back and forth. Here is some more code:

Toggle Switch:

import "./Styles.css";
import { useTheme } from "../ThemeContext";

const Switch = () => {
  const { theme, toggleTheme } = useTheme();
  return (
    <label className="switch">
      <input
        type="checkbox"
        defaultChecked={theme === "light"}
        onChange={toggleTheme}
      />
      <span className="slider round" />
    </label>
  );
};

export default Switch;

Paragraph:

    
const Paragraph = ({ children }) => {
    const { theme } = useTheme();
    return (
        <p
            style={{
            color: theme === "light" ? "black" : "white",
            }}
         >
         {children}
         </p>
    );
};

Can I use npm packges in a vanilla web page?

I have a simple web page made up of vanilla html, css and js files.

I’d like to be able to use the import { moment } from "moment" syntax in my js files but when I add npm to my proejct, install moment wiht npm install and use that syntax when I run my app using live-server I get an error:

Uncaught TypeError: Failed to resolve module specifier "moment". Relative references must start with either "/", "./", or "../".

Exploring React Shallow Copy Methods: Spread Operator vs Direct Assignment

I am currently working on a React project and encountered an interesting issue related to shallow copying objects. In my component, I have a form where I collect data, and I noticed that different methods of shallow copying the data object result in different behaviors.

Here are the three approaches I’ve tried:

Approach 1 (works)

const handleSubmit = async (e) => {
    e.preventDefault();
    actions.updateEmail(...Object.values(localEmailData));
    console.log(store);
};

Approach 2 (works but with console error)

const handleSubmit = async (e) => {
    e.preventDefault();
    actions.updateEmail(...localEmailData);
    console.log(store);
};

The console error reads:

Uncaught (in promise) TypeError: Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.

        

Approach 3 (won’t work)

const handleSubmit = async (e) => {
    e.preventDefault();
    actions.updateEmail(localEmailData);
    console.log(store);
};

Can someone explain the differences between these methods, and why Approach 2, although working, triggers a console error? Additionally, why doesn’t Approach 3 work?

My React component

    […]
    
    export const Home = () => {
        const { store, actions } = useContext(Context);
    
        const [localEmailData, setLocalEmailData] = useState({
            projectName: store.email.nombreDelProyecto,
            unsubscribeUrl: store.email.unsubscribeUrl,
            header: {
                link1: store.email.header.link1,
                image1: store.email.header.image1,
                alt1: store.email.header.alt1,
                link2: store.email.header.link2,
                image2: store.email.header.image2,
                alt2: store.email.header.alt2,
                link3: store.email.header.link3,
                image3: store.email.header.image3,
                alt3: store.email.header.alt3,
            },
            cta: {
                image: store.email.cta.image,
                link: store.email.cta.link,
            },[…]
});

        const handleInputChange = (e) => {
            setLocalEmailData({ localEmailData, [e.target.name]: e.target.value });
            console.log("localEmailData", localEmailData);
            console.log("Submitting form with data:", localEmailData);
        };
    
        const handleSubmit = async (e) => {
            e.preventDefault();
            actions.updateEmail(...Object.values(localEmailData));
            console.log(store);
        };
    
        return (
            <div className="mt-5">
                <div className="d-flex justify-content-center">
                    {/* Formulario de encabezado */}
                    <Form className="w-50" onSubmit={handleSubmit}>
                        […]
                        <div className="d-flex justify-content-center">
                            <Button type="submit" className="generar-correo">
                                Validate & Generate
                            </Button>
                            <Link to="/pocuromailbuilder" className="generar-correo">
                                <span>Go to </span>&nbsp;<span style={{ fontStyle: 'italic' }}>output</span>
                            </Link>
                        </div>
                    </Form>
                </div>
            </div>
        );
    
    };

Also, my action at flux.js is:

updateEmail: (newData) => {
                setStore({
                    ...getStore(),
                    email: {
                        ...getStore().email,
                        ...newData,
                    }
                });
            },

Any insights or explanations would be greatly appreciated. Thank you!