JS userscript Refused to connect because it violates the following content security policy directive [duplicate]

I am writing a tampermonkey script in JS that fetches data from google sheets.

 const url = 'https://docs.google.com/spreadsheets/d/...';
    await fetch(url)
    .then(res => res.text())
    .then(rep =>{
        data = JSON.parse(rep.substr(47).slice(0,-2));
        console.log(data);

I am getting the following error

Refused to connect to 'https://docs.google.com/spreadsheets/d/...' because it violates the following Content Security Policy directive: "connect-src 'self'

How do I fix this?

Nested Iframe doesn’t have content after reload on Mozilla

I have this problem on Mozilla (worked perfectly on Chrome) where the nested Iframe doesnt have content after reload (only empty header and body tag)

Somehow you can click on the search bar and enter (instead of reload) to open again and all iFrame will load as intended

The snippet below doesnt work on the playcode website. You should open it in localhost for it to work.
https://playcode.io/874440/

Body index.html

<body>
    <div>Index</div>
    <iframe id="iframe"></iframe>
    <script>
        (function () {
            var b = document.getElementById("iframe");
            b.setAttribute("src", "iframe.html?" + Math.random() * 100);
        })();
        window.addEventListener('beforeunload', function (event) {
            console.log('I am the 1st one.');
        });
        window.addEventListener('unload', function (event) {
            alert('unLoad')
        });
    </script>
</body>

body iframe.html

<body>
    <header>
        IFRAME1
    </header>
    <iframe id="iframe2"></iframe>
    <script>
        (function () {
            var b = document.getElementById("iframe2");
            b.setAttribute("src", "iframe2.html?" + Math.random() * 100);
        })();
        window.addEventListener('beforeunload', function (event) {
            console.log('frame 1 before unload.');
        });
        window.addEventListener('unload', function (event) {
            console.log('frame 1 unload.');
        });
        window.addEventListener('pagehide', (event) => {
            if (event.persisted === true) {
                console.log('This page *might* be entering the bfcache.');
            } else {
                console.log('This page will unload normally and be discarded.');
            }
        });
    </script>
</body>

Body iframe2.html

<body>
    <header id="h2">
        this is iframe 2
    </header>
    <script src="iframe2.js"></script>
</body>

I read something about bfcache, which is why i tried to put unload event to negate bfcache.

It seems thats not the issue.

Merging number of shapes to make a single svg element

Basically, its for performance improvement. In SVG, the more the number of elements, the less performance efficient it gets, or in simpler words, fps drops. I am trying to improve some performance issues in my SVG illustration library (ChelseaJS) when it comes to a large number of elements. Is there a way, I could merge shapes, for example, instead of two rectangle elements, it can be just one element.
ps: don’t suggest the tag, coz, it’s just like a box for keeping elements together.

Function to remove special character

I am new in programming. I need an example for a funciton that I need to do to learn. The function is below.

  • a function that accepts input from a user.
  • Then when the user submits this function will return a sorted arrangement that removes allspaces and symbols
  • then sorts ascending for alphabets on the left side and sorts descending for numerics.

Can I do all this in one string? better to be in HTML or JS? I need to see any.

I am having a problem to make my text delay, for that I am using setTimeout function [duplicate]

Please help me and tell how can I fix this problem
I have tried changing the format a lot but this problem is still there, actually I am beginner who has leant web developing from the internet only.

Here’s my code of html, css and JavaScript –

**HTML**
<div class="sub-heading">
      <h3>Wants high quality fini....... This place is for you</h3>
    </div>

**CSS**
.sub-heading {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: auto;
  transition: 3s;
  visibility: hidden;
}

**JavaScript**
let myTimeOut = setTimeout(myFunction, 3000);

function myFunction() {
    document.getElementsByClassName("sub-heading").style.visibility = "visible";
}

Please help me and tell how can I fix this problem
I have tried changing the format a lot but this problem is still there, actually I am beginner who has leant web developing from internet only.

JavaScript Event Handling – Select not changing

I am attempting to use JavaScript to change the image that is displayed based on the option selected from a dropdown menu.

Using chrome monitorevents() I am able to tell that the change event is being triggered, however the variable direction is not being changed.

If I change the assigned value of direction manually, as you can see commented out, the correct image will display.

I’m sure it’s something minor I’m overlooking, but I’ve been noodling at this pretty much all day.

I would appreciate anyone’s input.


    <div class="dropdown">
        <label for="choose-lighting" id="windowDirection">Which direction does your window face?</label>

        <select name="lighting" id="choose-lighting">
            <option value="empty">--- Direction ---</option>
            <option value="north">North</option>
            <option value="south">South</option>
            <option value="east">East</option>
            <option value="west">West</option>
        </select>
    </div>

    <div id="displayBox">
        <img src="" id="onDisplay">
    </div>

    <script>
        // var direction = document.querySelector("select");
        // var onDisplay = document.getElementById("onDisplay")
        var select = document.getElementById("choose-lighting");
        var direction = select.options[select.selectedIndex].text;
        console.log(direction);
        // var direction = "south";

        function chooseLighting() {

            // switch (direction) {
            //     case "north":
            //         document.getElementById("onDisplay").src = "images/lightguide_north.jpg";
            //         break;
            //     case "south":
            //         document.getElementById("onDisplay").src = "images/lightguide_south.jpg";
            //         break;
            //     case "east":
            //         document.getElementById("onDisplay").src = "images/lightguide_east.jpg";
            //         break;
            //     case "west":
            //         document.getElementById("onDisplay").src = "images/lightguide_west.jpg";
            //         break;
            //     default:
            //         document.getElementById("onDisplay").src = "images/lightguide_genericweb.jpg";
            //         break;
            // }

            if(direction == "North") {
                document.getElementById("onDisplay").src = "images/lightguide_north.jpg";
            }

            else if(direction == "South") {
                document.getElementById("onDisplay").src = "images/lightguide_south.jpg";
            }

            else if(direction == "East") {
                document.getElementById("onDisplay").src = "images/lightguide_east.jpg";
            }

            else if(direction == "West") {
                document.getElementById("onDisplay").src = "images/lightguide_west.jpg";
            }

            else {
                document.getElementById("onDisplay").src = "images/lightguide_genericweb.jpg";
            }

        }

        if (window.addEventListener) {
            window.addEventListener("load", chooseLighting, false);
        }

        else if (window.attachEvent) {
            window.attachEvent("onload", chooseLighting);
        }

        if (document.getElementById("choose-lighting").addEventListener) {
            document.getElementById("choose-lighting").addEventListener("change", chooseLighting, false);
            console.log(direction);
        }

        else if (document.getElementById("choose-lighting").attachEvent) {
            document.getElementById("choose-lighting").attachEvent("onchange", chooseLighting);
            console.log(direction);
        }

    </script>

FETCH JavaScript PHP process the data on the server sent with fetch

I have this doubt of how to process the data brought from my form, I am using javascript with a fetch to receive the data of the form, but I have the doubt of how I should process them in php, nor is the click event of the send button working, the problem is that the server seems not to be receiving the array sent from javascript with the data, agradesco if you give me any source to delve into the topic of fetch api, I am new to javascript and php

my Javascript

registrar.addEventListener("click", () => {
    fetch("../add.php", {
        method: "post",
        body: new FormData(frm) //frm es el id del formulario
    }).then(response => response.text()).then
        (response => {
            // console.log(response);
            // si la respuesta sel servidor es "ok" arroja una alerta personalizada
            if (response == "ok") {
                Swal.fire({
                    icon: 'success',
                    title: 'Registrado',
                    showConfirmButton: false,
                    timer: 1500
                })
                frm.reset();
            }
        }
        )
})
  <form action="" method="post" id="frm">
                      <div class="form-group">              
                       <br>      

                    <div class="form-group">
                        <div class="form-group">
                          <input type="text" name="name_usu" id="name_usu" class="form-control form-control-md" placeholder="Nombre completo" required >
                        </div>
                        <input type="text" name="phone_usu" id="phone_usu" class="form-control form-control-md" placeholder="Numero de teléfono" required>
                      </div>

                        <input type="email" name="nom_usu" id="nom_usu" class="form-control form-control-md" placeholder="Email" required></div>
                        <input type="text" name='torreApto' id="Torre_apto" class="form-control form-control-md" placeholder="Torre y apartamento" required>
                      <label for="FormControlSelect1" class="text-light">Escoja tipo de residente</label>
                      <select class="form-control" name="sel_apto" id="sel_apto" required>
                        <option selected>Propietario</option>
                        <option selected>Arrendado</option>
                        <option selected>Otro</option>
                      </select>
                          
                          <div class="form-group">
                            <label for="Textarea1" class="text-light">Mensaje a enviar</label>
                            <textarea class="form-control" name="mensaje" id="Textarea1" rows="3"></textarea>
                          </div>
                          <br>  
                        <input type="button" class="btn btn-outline-light btn-block border-light text-light font-weight-bold" value="registrar" id="registrar">
                  </form>

addRegister.php

enter if (isset($_POST)) {
$nombre = $_POST['name_usu'];
$telefono = $_POST['phone_usu'];
$email = $_POST['nom_usu'];
$torreApto = $_POST['torreApto'];
$arrendado = $_POST['sel_apto'];
$mensaje = $_POST['mensaje'];
require("connect.php");

// script guardando en la base de datos 
$query = $con->prepare("INSERT INTO informacion(nombre,telefono,email,torreApto,arrendado,mensaje) VALUES (:nom, :tel, :ema, :torr, :arr, :men)");
$query->bindParam(":nom", $nombre);
$query->bindParam(":tel", $telefono);
$query->bindParam(":ema", $email);
$query->bindParam(":torr", $torreApto);
$query->bindParam(":arr", $arrendado);
$query->bindParam(":men", $mensaje);

//ejecuta el script 
$query->execute();
$con = null;
echo "ok";

}

React/Nextjs | Cannot figure out how to properly loop image back to start/end when pressing previous and next arrows

I am using heroicons, tailwindCSS, nextjs/react.

I have tried creating a useState for the index and using useEffect to update it every time. selectedIMG has a state but that didnt work as well. I cannot seem to understand why it is not looping the array when clicking on the arrow icons.

  const [selectedIMG, setSelectedIMG] = useState();


        {/* Popup Image */}
        {selectedIMG && (
          <div className="fixed top-0 z-50 w-[100vw] h-[100vh] flex justify-center items-center backdrop-blur-sm select-none">
            <div className="absolute w-[100vw] h-[100vh] bg-custom-black bg-opacity-60 " />
            <XIcon
              className="w-12 h-12 absolute top-10 right-10 cursor-pointer z-10 p-2 border rounded-full xl:scale-150 bg-opacity-10 bg-white"
              onClick={() => setSelectedIMG()}
            />
            <ArrowLeftIcon
              className="absolute text-white z-50 w-12 h-12 p-2 border rounded-full left-5 lg:left-[10vw] xl:scale-150 cursor-pointer shadow-2xl bg-white bg-opacity-10"
              onClick={() => {
                const selectedIndex = galleryImages.findIndex(
                  (item) => item == selectedIMG
                );

                console.log(selectedIndex);

                if (selectedIndex <= 0) {
                  setSelectedIMG(galleryImages[galleryImages.length]);
                } else {
                  setSelectedIMG(galleryImages[selectedIndex - 1]);
                }
              }}
            />
            <ArrowRightIcon
              className="absolute text-white z-50 w-12 h-12 p-2 border rounded-full right-5 lg:right-[10vw] xl:scale-150 cursor-pointer shadow-2xl bg-white bg-opacity-10"
              onClick={() => {
                const selectedIndex = galleryImages.findIndex(
                  (item) => item.src == selectedIMG.src
                );

                if (selectedIndex == galleryImages.length) {
                  setSelectedIMG(galleryImages[0]);
                } else {
                  setSelectedIMG(galleryImages[selectedIndex + 1]);
                }
              }}
            />
            <div className="relative w-full h-3/4">
              <Image
                priority
                layout="fill"
                objectFit="contain"
                src={selectedIMG.src}
                alt=""
              />
            </div>
          </div>
        )}
        {/*  */}
        <section>
          <PageHeader title={"Gallery"} info={"Showcase of work"} />

          <div className="grid grid-cols-2 sm:grid-cols-3  gap-y-1 gap-x-1 justify-center items-center mt-5">
            {galleryImages.map((img) => (
              <div
                className="relative rounded-sm min-w-[100px] w-full h-full overflow-hidden mx-auto p-3 cursor-pointer"
                key={img.src}
                whileHover={{
                  scale: 1.1,
                  transition: {
                    ease: [0.6, 0.01, -0.05, 0.95],
                  },
                }}
                onClick={() => setSelectedIMG(img)}
              >
                <div>
                  <Image
                    width={"100%"}
                    height={"100%"}
                    layout="responsive"
                    objectFit="cover"
                    src={img.src}
                    alt={img.caption}
                  />
                </div>
              </div>
            ))}
          </div>
        </section>

React RTK, slow UI updates

I’m having issues where the state of my app updates very slowly. Here’s an image of my main page.

enter image description here

Now when you click on a blue item in the map, it’s associated item should be highlighted red in the list below the map.

This works, but it takes like 1-3 seconds to update. It’s slow.

The store is in the root App component:

function App() {
  return (
    <div className="App">
      <Provider store={store}>
        <Header></Header>
        <Main />
      </Provider>
    </div>
  );
}

The map and the list of items are in their own component in <Main />:

  <Map></Map>
  <MainSub></MainSub>

<Map/> dispatches an event to the store on a click event called setActive.

  function handleMarkerClick(data) {
    console.log("click :" + data.name);
    dispatch(setActive({ res: data._id.toString() }));
  }

<MainSub/> contains the list and updates according to state change.

  const restaurantList = useSelector((state) => {
    console.log(state.restaurantSlice);
    return state.restaurantSlice;
  }, shallowEqual);

This is my slice:

import { createAsyncThunk, createSlice, current } from "@reduxjs/toolkit";
const axios = require("axios");
export const fetchRestaurants = createAsyncThunk(
  "fetchRestaurants",
  async (teamId) => {
    console.log(teamId);
    var data = await axios.get("http://localhost:3000/getRestaurant", {
      params: {
        lon: -72.631119,
        lat: 42.206242,
        radius: 1,
      },
    });

    return data.data;
  }
);
export const restaurantSlice = createSlice({
  name: "restaurant",
  initialState: {
    data: { count: 0, data: [] },
    currentActive: 0,
    loading: "",
  },
  reducers: {
    setActive: (state, action) => {
      var getID = action.payload.res;

      state.data.data.map((obj) => {
        if (obj._id === getID) {
          obj.isActive = true;
        }
      });
      state.data.data.map((obj) => {
        if (obj._id === state.currentActive) {
          obj.isActive = false;
        }
      });

      state.currentActive = action.payload.res;
    },
    setRestaurant: (state, action) => {},
    getRestaurant: (state, action) => {},
  },
  extraReducers: (builder) => {
    builder.addCase(fetchRestaurants.fulfilled, (state, action) => {
      console.log(current(state));
      action.payload.data.forEach((x) => {
        x.isActive = false;
      });
      state.data = action.payload;
      state.data.data[0].isActive = true;
      state.currentActive = state.data.data[0]._id;
      state.loading = "loaded";
    });
  },
});

Also, the extraReducer is what gets the list.

(I don’t know if that’s the root issue)

I understand that createSlice uses immer behind the scenes so the mutations to the list in setActive shouldn’t be a problem I think. Also if you look in the chrome dev tools, you’ll see that the console.log in useSelector logs twice. I’m not sure why that’s happening since setActive is only dispatched once.

Here’s a link to the code in github. There’s not a lot of code. Only a few components that are self explanatory. https://github.com/CTMatt23/overflow

Thank you for any input. Again this is React Redux Toolkit.

How JavaScript uses variables when reading json

Like the title, I tried to use variables when reading json, but it didn’t work (

fetch('https://lolimstatic.ml/counts/apis.json').then(
(response) => {
    response.json().then((data) => {
        const apiListFrame = document.querySelector('#als');
        const api = document.createElement('a');
        api.classList.add('btns');
        api.classList.add('button');
        api.classList.add('apilist');
        var rns = Math.round(Math.random()*10);
        colors = ["blue","red","white","orange","pink","green","yellow","skyblue","purple","gray"];
        api.style.background = colors[rns];
        api.style.width = '200px';
        var lstd = Math.round(Math.random()*data[0].counts);
        api.href = 'https://docs.lolimapis.ml/API/'+ data[0].list[lstd] +'/';
        lnm = data[0].list[lstd];
        var xhr = new XMLHttpRequest;
        xhr.open("GET", 'https://lolimstatic.ml/counts/apis/zh.json');
        xhr.send();
        xhr.onreadystatechange = function () {
            if (xhr.readyState = 4) {
                const res = xhr.responseText;
                // Here is variables Json
                api.innerText = res.lnm;
                apiListFrame.appendChild(api);
            }
        }
    })
}
)

I think it variables to this:

{
    "lnm": ""
}

But I want variables to this(Suppose the lnm variable is BingImage):

{
    "BingImage": "每日Bing图获取"
}

Can i reload div automaticly without click events?

i want to togle between 2 carts icon,one display when the cart is empty the second when is not,

<div id="div-icon-cart">
        <span class="tools-icon">



        <?php if ( ! WC()->cart->is_empty() ) { ?>
                                

    <img  decoding="async" src="https://txxxx.com/uploads/cart.svg" class="custom-icon" alt="" height="20.738" width="17.626">      
                <?php } else{ ?>


<!-- begin snippet: js hide: false console: true babel: false -->

but the problem is that the cart icon doesn’t change immediately,i need to refrech the page to upload cart icon.
for that i tried to reload div which contains my cart icon

    $document.ready(function(){
        $('#div-icon-cart').load();
        setInterval{fonction(){
            $('#div-icon-cart').load();
        },3000};
    });

but doesn’t work and i don’t know why.i would be grateful for any help

NB:

  • i cant trriger an event like onClick.
  • the right solution for me is to reload div automaticly

Error when uploading image to firebase using react js

I am having issues uploading my picture to firebase, the problem seems to stem from [ firebase storage ] i’ve tried multiple iterations of it and still no luck.

in the console, i saw this error:

FirebaseError: Firebase: No Firebase App ‘[DEFAULT]’ has been created – call Firebase App.initializeApp() (app/no-app).

   import React, { useState, useEffect } from "react";
import { Paper } from "@mui/material";
//import axios from "axios";
import authHeader from "../../features/authentication/AuthHeader";
//import {storage} from "./firebase.js";
import {getStorage,ref,uploadBytes} from 'firebase/storage';

function UserProfile() {
  const [user, setUser] = useState({});

  async function fetchUser() {
    const response = await fetch("http://localhost:9005/getProfile", {
      headers: authHeader(),
    });
    const fetchedUser = await response.json();
    console.log(fetchedUser);
    setUser(fetchedUser);
  }

  useEffect(() => {
    fetchUser();
  }, []);

  //firebase upload
  const allInputs = { imgUrl: "" };
  const [imageAsFile, setImageAsFile] = useState("");
  const [imageAsUrl, SetImageAsUrl] = useState(allInputs);

  const handleImageAsFile = (e) => {
    const image = e.target.files[0];
    setImageAsFile((imageFile) => image);
  };

  const handleFireBaseUpload = e =>{
    e.preventDefault();
    console.log('uploading pic');
    if(imageAsFile===''){
      alert(`image format not supported${typeof(imageAsFile)}`);
    }

    const storage = getStorage();
    const storageRef = ref(storage,'tet');

    uploadBytes(storageRef,imageAsFile).then((snapshot)=>{
      alert('uploading');
    });
    //const uploadTask = storage.ref(`/images/${imageAsFile.name}`).put(imageAsFile);
  }
 

  return (
    <>
      

      <Paper
      
        elevation={6}
        style={{ margin: "10px", padding: "15px", textAlign: "left" }}
        key={user.user_id}
      >
      <div className="pfp">
          <form onSubmit={handleFireBaseUpload}>
            <input type="file" onChange={handleImageAsFile} />
            <p>hgk</p>
            <button>test</button>
          </form>
        </div>
        First Name: {user.firstName}
        <br />
        Last Name: {user.lastName}
        <br />
        Email: {user.email}
        <br />
        Phone: {user.phone}
      </Paper>
    </>
  );
}
export { UserProfile as default };

this is the firebase js

import {initializeApp} from "firebase/app";
import firebase from "firebase/compat/app"
import "firebase/storage" ;




const firebaseConfig = {
    apiKey: "AIzaSyB8vxklg6-m-G8vUYANQ45uzD4OTIa4gsQ",
    authDomain: "dart-cart-273ad.firebaseapp.com",
    projectId: "dart-cart-273ad",
    storageBucket: "dart-cart-273ad.appspot.com",
    messagingSenderId: "41403665604",
    appId: "1:41403665604:web:3cfb4b0c15e705451fcd91"
  };
  //initilize firebase
  firebase.initializeApp(firebaseConfig);

  const storage = firebase.storage();

  export{
    storage, firebase as default
  }