unsafe inline. Unity webGL build

I made a build on unity WEB GL, when I run it on the local host, I get the following error

tab.js:1 Refused to execute inline script because it violates the following Content Security Policy directive: “script-src ‘self’ ‘wasm-unsafe-eval’ ‘inline-speculation-rules'”. Either the ‘unsafe-inline’ keyword, a hash (‘sha256-kPx0AsF0oz2kKiZ875xSvv693TBHkQ/0SkMJZnnNpnQ=’), or a nonce (‘nonce-…’) is required to enable inline execution.

I tried changing the browser, without success

How to Organize HTML Tags like , , and in an Article Page for a Web Application?

I’m developing a web application with article pages and am struggling with how to organize HTML tags such as <h1>, <h2>, <ul>, etc. I want to create a system that allows writers to format articles easily without needing to understand HTML.

I initially attempted to use regex to replace custom markers in the text with corresponding HTML tags. Here’s what I tried:

loadArticlePage: (id) => {
 return `${articleData.content
    .replace(/{{{{{([^}]+)}}}}/g, "<h4>$1</h4>")
    .replace(/{{{{([^}]+)}}}}/g, "<h3>$1</h3>")
    .replace(/{{{([^}]+)}}}/g, "<h2>$1</h2>")
    .replace(/(((([^)]+))))/g, "<p>$1</p>")
  }
  </div>
 </div>`
;

However, this approach seems complicated for the article writers to use effectively. What is a better way to organize these HTML tags or a more user-friendly method for writers to format articles in the application? Any suggestions or best practices would be greatly appreciated!

I tried using a series of regular expressions to replace custom markers in the article content with HTML tags. My goal was to allow writers to use a simple markup format that would be converted into the correct HTML.

how to import “mongoose” library into html

me want to import a mongoose library to my website(into html code), but I cant`t do this. I tryed import a ‘mongoose/index.js’ file, but I was only able to import this file and not the entire library. How can I import this library into my html code?
P.S. In developer console was written “require is not defined”

getBoundingClientRect() returns the same values for different elements

This is my first project with HTML so, I’m sorry if this is a stupid question.
I have a column of images on the left and right and between them a column of text.
My problem is in the adjustImageVisibility() function.
I want to get the position of each image because I want to hide images that are lower then the text.
I managed to get the position for the last element in the text column, but when I check the positions for the images, img.getBoundingClientRect() gives the same values for each image.

bottom : -134.1999969482422
height : 0
left   : 5
right  : 5
top    : -134.1999969482422
width  : 0
x      : 5
y      : -134.1999969482422

The images are all 512 × 768 px and renderd as 127 × 190 px.

Here is my code snippet

const imageFolder = 'images/'; // Path to the local folder containing the images
const totalImages = 26; // (Total number of images in the folder) / 2

// Function to pad image name with zeros
function padImgName(i) {
  let imgName;
  if (i < 10) {
    imgName = `00${i}`;
  } else if (i < 100) {
    imgName = `0${i}`;
  } else {
    imgName = `${i}`;
  }
  return imgName;
}

// Function to load images from the local folder
function loadImages() {
  const leftImages = document.getElementById('left images');
  const rightImages = document.getElementById('right images');

  // Assuming images are named as 000.jpg, 001.jpg, etc.
  var imageNumber = 0;
  for (let i = 0; i <= totalImages; i++) {
    // left
    const leftImg = document.createElement('img');
    const leftImgName = padImgName(imageNumber);

    leftImg.src = `${imageFolder}${leftImgName}.jpeg`;
    leftImg.alt = `Image ${i} left`;
    leftImg.id  = `Image ${i} left`;

    leftImages.appendChild(leftImg);

    imageNumber++;

    // right
    if (imageNumber <= totalImages * 2) {
      const rightImg     = document.createElement('img');
      const rightImgName = padImgName(imageNumber);

      rightImg.src = `${imageFolder}${rightImgName}.jpeg`;
      rightImg.alt = `Image ${i} right`;
      rightImg.id  = `Image ${i} right`;

      rightImages.appendChild(rightImg);

      imageNumber++;
    }
  }
}

// Function to adjust the visibility of the images
function adjustImageVisibility() {

  // get bottom of Text 
  const centerDiv   = document.getElementById('center text');
  const lastElement = centerDiv.lastElementChild;
  const rect        = lastElement.getBoundingClientRect();
  const textBottom  = rect.bottom + window.scrollY;
  console.log(textBottom);

  // left
  for (let i = 0; i <= totalImages; i++) {
    const img  = document.getElementById(`Image ${i} right`);
    const rect = img.getBoundingClientRect();
    console.log(rect);
  }
}

// Load images from the local folder when the page loads
window.onload = function() {
  loadImages();
  adjustImageVisibility();
};
/* --------------- body --------------- */

body {
  margin: 0;
  padding: 0;
  height: 100vh;
  display: flex;
  font-family: Arial, sans-serif;
}


/* --------------- unused --------------- */

.column {
  display: flex;
  flex-direction: column;
  /* Stack items vertically */
  align-items: top;
  justify-content: top;
}


/* --------------- columns --------------- */

.left,
.right {
  /* for the images */
  width: 20%;
  padding: 5px;
}

.center {
  /* for the text */
  width: 100%;
  /* Adjusted to fill the remaining space */
  padding: 20px;
  text-align: left;
}


/* --------------- images --------------- */

img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}


/* --------------- title --------------- */

h1 {
  text-align: center;
}


/* --------------- horizontal lines --------------- */

hr {
  width: 100%;
}

hr.fox {
  width: 80%;
  border: none;
  border-top: 2px solid;
  overflow: visible;
  color: black;
  text-align: center;
}

hr.fox::after {
  display: inline-block;
  content: '^.^';
  position: relative;
  /* Use absolute positioning */
  top: -10px;
  /* Adjust the position as needed */
  background: white;
  /* Uncomment if needed */
  padding: 0 4px;
  /* Uncomment if needed */
}


/* --------------- for the ascii art --------------- */

pre {
  text-align: center
}
  <div class="left" id="left images"></div>

  <div class="center" id="center text">
    <h1>Azul's Blog</h1>

    <pre style="text-align: center">
        ASCII ART
        </pre>
    <p>
      text<br>
      <br>text<br>
      <br>text<br>
      <br>text<br>
      <br>text<br>
      <br>text<br>
      <br>text<br>
      <br>text<br>
      <br>text<br>
    </p>
    <hr class="fox">
    <p>
      text<br>
      <br>text<br>
      <br>text<br>
      <br>text<br>
      <br>text<br>
      <br>text<br>
      <br>text<br>
      <br>text<br>
      <br>text<br>
    </p>
    <hr class="fox">
    <p>
      text<br>
      <br>text<br>
      <br>text<br>
      <br>text<br>
      <br>text<br>
      <br>text<br>
      <br>text<br>
      <br>text<br>
      <br>text<br>
    </p>
    <hr class="fox">
  </div>
  <div class="right" id="right images"></div>
  

code:

How to cancel a pop up?

so I am making a to-do list. When you remove a task from the red trash button, it asks you if you want to delete it or not. And “cancel” should remove the question and the task will stay. But it doesn’t, the question stays and I have looked everywhere, but nothing works and the question doesn’t disappear. Can you help me with removing the question when you click “cancel”. Here is code(JS):

document.addEventListener('DOMContentLoaded', () => {
const textareaEle = document.getElementById('j');
textareaEle.addEventListener('input', () => {
    textareaEle.style.height = 'auto';
    textareaEle.style.height = `${textareaEle.scrollHeight}px`;
});
function myFunction(){
const body = document.getElementById("body");
const whole = document.getElementById("whole");
const dif = document.getElementById("dif");
const div = document.getElementById("copy");
const sauce = document.getElementById("sauce");
const textareaEle = document.getElementById('j');
let checkbox = document.createElement("input");
checkbox.setAttribute("type", "checkbox", "class", "checkbox");
let paragraph = document.createElement("p");
paragraph.setAttribute("class", "checkbox");
let konq = document.createTextNode(textareaEle.value);
let line = document.createElement("br");
const hr = document.createElement("hr");
hr.setAttribute("id", "hr")
let sauceItem = document.createElement("div");
let del = document.createElement("input");
del.setAttribute("class", "del",)
del.src = "trash2.png";
del.type = "image"; 
sauceItem.classList.add("sauce-item");
let sauceI = document.createElement("div");
sauceI.classList.add("sauce-i");
paragraph.appendChild(konq);
sauceI.appendChild(hr);
sauceItem.appendChild(checkbox);
sauceItem.appendChild(paragraph);
sauceItem.appendChild(del);
sauceItem.appendChild(line);
sauce.appendChild(sauceItem);
sauce.appendChild(sauceI);
del.onclick = function(){
    let popup = document.createElement("div");
    popup.setAttribute("id", "overlay")
    let textche = document.createElement("p");
    textche.textContent = "Are you sure you want to delete it? Once removed, it can't be restored."
    let r = document.createElement("button");
    r.textContent = "remove"
    r.setAttribute("id", "r")
    c = document.createElement("button");
    c.textContent = "cancel"
    c.setAttribute("id", "c")
    hhr = document.createElement("hr");
    hhr.setAttribute("id", "hrr")
    popup.appendChild(textche);
    popup.appendChild(hhr);
    popup.appendChild(r);
    popup.appendChild(c);
    sauce.appendChild(popup);
    c.onclick = function() {
        //cancel pop up
    }
}

};

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>Title of the document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body id="body">
    <script src="index.js"></script>
<div id="dif">
    <p1 id="f">To-do list</p1>
    <hr>
    <div id="copy">
    <textarea type="text" id="j" placeholder="Enter here" rows="1"></textarea>
    <button id="e" onclick="myFunction()">Add</button>
    <hr>
    <div id="sauce">
</div>
</div>
</div> 
</body>

</html>

Why useEffect called Multiple times when axios is present inside

I am just now Learning React JS, stuck with the following issue
useEffect is called Multiple Times, even when state value is passed in Dependencies. How to fix it?

import axios from 'axios';
import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom';

const ViewProfileUseEffect = () => {
    const [userList, setUserList] = useState([]);
    const naviagte = useNavigate();
    useEffect(() => {
        axios.get("http://localhost:4000/users").then((response) => {
            setUserList(response.data);
            console.log('I am inside useEffect');
        }).catch((error) => {
            alert("Something went wrong")
        })
    }, [userList]);
function handleProfile(id) {
        naviagte(`/profile/${id}`);
    }

    function deleteProfile(id) {
        axios.delete(`http://localhost:4000/users/${id}`).then((response) => {
            console.log(`Delete Response Data ${response.data}`);
        }).catch((error) => {
            alert("Something went Wrong");
        })
    }
    return (
        <>
            <h3>View Profile</h3>
            <div className='container' style={{ backgroundColor: 'bisque', width: '500px', padding: '20px', borderRadius: '5px' }}>
                <table className='table'>
                    <thead>
                        <tr>
                            <th scope='col'>UserName</th>
                            <th scope='col'>Email ID</th>
                            <th scope='col'>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        {userList.map((user) => {
                            return (
                                <tr key={user.id}>
                                    <td>{user.userName}</td>
                                    <td>{user.userEmail}</td>
                                    <td>
                                        <button className="btn btn-warning" onClick={() => handleProfile(user.id)}>View Profile</button>
                                        <button className="btn btn-danger" onClick={() => deleteProfile(user.id)}>Delete Profile</button>
                                    </td>
                                </tr>
                            )
                        })}
                    </tbody>
                </table>
            </div>
        </>
    )
}

export default ViewProfileUseEffect

The Output I got

enter image description here

“I am inside useEffect” is coming in console multiple times endlessly

How to stop it?

JavaScript Broadcastchannel eventlistener not triggering when posting message

I have the following html file. When I open it the console only shows “BroadcastChannel created …” and “Posting message to channel”. Neither the eventlistener nor the onmessage function triggers.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BroadcastChannel Simple Test</title>
</head>

<body>
    <script>
        // Create a BroadcastChannel
        const messageChannel = new BroadcastChannel('newMessageChannel');
        console.log("BroadcastChannel created:", messageChannel);

        // Set up the message event listener
        messageChannel.onmessage = (event) => {
            console.log("new message received on message!", event.data);
        };
        messageChannel.addEventListener('message', (event) => {
            console.log("new message received eventlistener!", event.data);
        });

        // Immediately post a message to the channel
        setTimeout(() => {
            console.log("Posting message to channel");
            messageChannel.postMessage("data");
        }, 1000);
    </script>
</body>

</html>


I tested it on two different machines in two different browsers.

TypeError: Cannot read properties of undefined (reading ‘trim’)

how u doing?

I using this PHP validation below to send a http response to a javascript function, but I’m getting the error “TypeError: Cannot read properties of undefined (reading ‘trim’)”.

Can anyone help me with to identify where should a change to fix this typeerror?

PHP

    if(!$validate_status) {
      header($_SERVER["SERVER_PROTOCOL"]." 400 Bad Request");
    } else {
      header($_SERVER["SERVER_PROTOCOL"]." 200 OK");
    }

Javascript

function validate_submit(thisForm, action, formData) {
    fetch(action, {
      method: 'POST',
      body: formData,
      headers: {'X-Requested-With': 'XMLHttpRequest'}
    })
    .then(response => {
      if( response.ok ) {
        thisForm.querySelector('.loading').classList.remove('d-block');
        thisForm.querySelector('.sent-message').classList.add('d-block');
        thisForm.reset();         
      } else {
        throw new Error(`${response.status} ${response.statusText} ${response.url}`); 
      }
    })
    .then(data => {
      thisForm.querySelector('.loading').classList.remove('d-block');
      if (data.trim() == 'OK') {
        thisForm.querySelector('.sent-message').classList.add('d-block');
        thisForm.reset(); 
      } else {
        throw new Error(data ? data : 'Form submission failed and no error message returned from: ' + action);
      }
    })
    .catch((error) => {
      displayError(thisForm, error);
    });
  }

I tried to debug with chrome dev tools, but with no success. I couldn’t find out why data content sent from php is undefined and I don’t know how to fix it.

pls help, im just struggling with my project

Create a program that will demonstrate operations in a queue:

size of the queue is 5
operations: insert, remove and empty.

answers? probably.

hehssjsjshshshshsjsjsjsjsjsjsjssjsjsjsjsjsjsjsjsjsjsjsjsjsjsjsjsjsjsjsjsjsjsjsjsjssjsjsnshshshshshshshshshshshshshshshshsbsbsbshsbsbshsbsbsb

Embedded array data retrieval in MongoDB Atlas

I have game data in JSON format in my MongoDB Atlas. i have tried to retrieve all games player 1 has played in whole tournament though I’m not able to get anything returned to me even when using MongoDB Compass I was able to show all games from type played but not specific ones for getting more data after that would be easier I hope when the restrictions are made correctly

Part of one game JSON data database is holding all games

{
    "num": 12033,
    "name": "Team Elimination",
    "type": "team",
    "time": 0,
    "gamePlayed": 360,
    "dura": 420,
    "sbtype": "STANDARD_TEAM",
    "showPower": false,
    "showHealth": true,
    "totalPlayers": 20,
    "totalTeams": 4,
    "teams": [
        {
            "id": 1,
            "name": "Blue team",
            "pos": 1,
            "stats": {
                "score": 3730,
                "totalPlayers": 5,
                "totalTagsFor": 28,
                "totalTagsAgainst": 20,
                "totalShots": 277,
                "scoreTimeLine": {
                },
                "isEliminated": false
            },
            "colour": "BLUE",
            "players": [
                {
                    "id": 21,
                    "alias": "player 1",
                    "tid": 1,
                    "pos": 1,
                    "omid": 5116714,
                    "stats": {
                        "hp": 3,
                        "score": 1430,
                        "tagson": 8,
                        "tagsby": 5,
                        "actualScore": 1430,
                        "tagRatio": 160,
                    },
                },
                {
                    "id": 30,
                    "alias": "player 2",
                    "tid": 1,
                    "pos": 2,
                    "omid": 5167552,
                    "stats": {
                              },
}

This is what I have in my code, in my backend side:

  const handleSearch = async (e) => {
    e.preventDefault();
    try {
      const response = await axios.get(`http://localhost:3001/events/${searchTerm}`);
      console.log('Response:', response);
      setPlayerData(response.data);
      setError('');
    } catch (err) {
      setPlayerData([]);
      console.log(err)
      setError('Player not found or an error occurred');
    }
  };

Server side:

app.get('/players/:alias', async (request, response) => {
    const alias = request.params.alias.toLowerCase();

    try {
      const events = await Event.find({'games.elim.teams.players.alias': alias});
      console.log('pelaajan nimi', events)
      const players = events.flatMap(event =>
        event.games.elim.flatMap(games =>
          event.games.elim.players.filter(player => player.alias.toLowerCase() === alias),
          console.log(event.teams.flatMap(team => team.players))
        )
      );

      if (events.length === 0) {
        return response.status(404).json({ error: 'Player not found' });
      };
      // Filter to get player details
  
      response.json(players);
    } catch (error) {
        console.log(error)
      response.status(500).send({ error: 'Error fetching player data' });
    }
  });

and event schema for games in server side code.

Games are in schema that’s in

due to error wasnt able to write schema

in here we expect that all game data are in games.elim.

The problem is that I haven’t been able to get successful return from player found either from correct “alias” and after that from all games that player with that alias has played for more data

ForbiddenError: invalid csrf token at doubleCsrf

I’ve been trying to implement CSRF into my code for a dummy social media application. I have been trying to use double CSRF (CSRF-CSRF) but I just can not get it to work. Every time I get past my Sign In page i get the dreaded “ForbiddenError: invalid csrf token at doubleCsrf”.

Below is my App.js:

const path = require('path');

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session);
const { doubleCsrf: csrf } = require('csrf-csrf');
const cookieParser = require('cookie-parser');

const User = require('./models/users');

const MONGODB_URI = "mongodb+srv://#######@cluster0.ecbbaof.mongodb.net/Personal?retryWrites=true&w=majority&appName=Cluster0"

const app = express();
const store = new MongoDBStore({
    uri: MONGODB_URI,
    collection: 'sessions',
});
const csrfProtection = csrf({
    getSecret: () => 'supersecret',
    getTokenFromRequest: (req) => req.body._csrf,
});

app.set('view engine', 'ejs');
app.set('views', 'views');

const mainRoutes = require("./routes/main")
const authRoutes = require("./routes/auth");

app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(
    session({
        secret: 'my secret',
        resave: false,
        saveUninitialized: false,
        store: store,
    })
);
/** CSRF-CSRF PACKAGE */
app.use(cookieParser('supersecret'));
app.use(csrfProtection.doubleCsrfProtection);

app.use((req, res, next) => {
    if (!req.session.user) {
        return next();
    }
    User.findById(req.session.user._id)
        .then((user) => {
            req.user = user;
            next();
        })
        .catch((err) => console.log(err));
});

app.use((req, res, next) => {
    res.locals.isAuthenticated = req.session.isLoggedIn;
    res.locals.csrfToken = req.csrfToken();
    next();
});


app.use(mainRoutes);
app.use(authRoutes);

mongoose
    .connect(MONGODB_URI)
    .then((result) => {
        app.listen(3001);
        console.log("connected")
    })
    .catch((err) => {
        console.log(err);
    });

Here is also my HTML template. I am using EJS:

<form action="/signup" method="POST">
                <div class="form-control">
                    <label for="email">E-mail</label>
                    <input type="email" name="email" id="email">
                </div>
                <div class="form-control">
                    <label for="username">Username</label>
                    <input type="text" name="username" id="Username">
                </div>
                <div class="form-control">
                    <label for="password">Password</label>
                    <input type="password" name="password" id="password">
                </div>
                <input type="hidden" name="_csrf" value="<%= csrfToken %>" />
                <button class="btn" type="submit">Sign up</button>
            </form>

I’ve tried everything things like clearing browser cache, & configuring CSRF settings and still nothing. I’m pretty new to things like this so please excuse me on that.

error always seems to be at the “const csrfProtection = csrf” section

If anyone know anything I’m doing wrong please point it out 🙂

Twitter (X) API: Retrieving liked tweets (from my own Twitter account) now that Twitter has anonymized likes

I have an app written in JavaScript that was able to retrieve all liked tweets for my own account earlier this year. However, once Twitter began anonymizing likes, the app no longer works and I can’t figure out how to get it to work now.

This was my OLD code to make the request (was working earlier this year):

const getdata = async () => {
  
  const url = `https://api.twitter.com/2/users/${twitterId}/liked_tweets`;
  
  const response = await needle("get", url, params, {
    headers: {
      "User-Agent": "v2LikedTweetsJS",
      authorization: `Bearer ${token}`
    },
  });

  console.log(response);
}

The new API seems to require OAuth and some cryptography, but I can’t figure it out. This is my NEW code that I’ve been messing around with, but can’t get working and feel like I’m quite lost:

const OAuth = require('oauth-1.0a');
const crypto = require('crypto');

const getdata = async () => {

  // Initialize
  const oauth = OAuth({
    consumer: {
      key: consumer_key,
      secret: consumer_secret,
    },
    signature_method: 'HMAC-SHA1',
    hash_function(base_string, key) {
      return crypto
          .createHmac('sha1', key)
          .update(base_string)
          .digest('base64')
    },
  });
  
  const url = `https://api.twitter.com/2/users/${twitterId}/liked_tweets`;

  const request_data = { url, method: 'POST' };
 
  const token = {
    key: access_token,
    secret: access_token_secret,
  }

  const response = await needle("post", url, params, {
    headers: {
      "User-Agent": "v2LikedTweetsJS",
      authorization: `Bearer ${token}`,
      headers: oauth.toHeader(oauth.authorize(request_data, token))
    },
  });
  
  console.log(response);
  
}

This is the error message I get from my new code:

{
  "title": "Method Not Allowed",
  "detail": "Method Not Allowed",
  "type": "about:blank",
  "status": 405
}

Can anyone help me figure out how to retrieve my own liked tweets?

JS String interpolation with object keys

I know this question has been already answered a lot, but I am curious why JavaScript and even TypeScript are not able to read the following code and throw a Syntax error:

const someVariable = 'abcd abcd some text'
const someObject = {
  `${someVariable}andSomethingElse`: 'someValue'
}

The current Syntax requires me to store that in another variable, and call it with an “array-like-syntax”, which is a bit annoying:

const someVariable = 'abcd abcd some text'
const objectKey = `${someVariable}andSomethingElse`
const someObject = {
  [objectKey]: 'someValue'
}

I’m curious why there is not even a change request in that regard, because it seems like such a useful thing, but not even TypeScript seems to support it (internally the transpiler could still turn it into the syntax as JS requires it).

I am curious, because honestly I don’t see anything wrong with this change, as it makes the lives of devs just easier.

So my question is: Why is this not possible in the year 2024?

JavaScript Issue with Dynamic Image Gallery

I’m designing a website for Reborn Auto Body, and I’m running into an issue with a JavaScript feature.Has anyone encountered this problem before or have any advice on how to resolve it?

I’ve set up a dynamic gallery to showcase before-and-after images of car repairs, but the images aren’t loading correctly when switching between categories. Initially, everything loads fine, but when I click on a different category, some images don’t appear until I refresh the page. I’m using vanilla JavaScript and think it might be an issue with event listeners or caching.