cancel fetch in javascript [closed]

Display multiple markers and get information from the same API no matter which marker is clicked. (Register the function to fetch in the event handler.)
After a marker is clicked and a fetch is started, we want to cancel the previously started fetch before another marker is clicked and another fetch is started.
I would prefer to use AbortController for the standard function.
I would like to make the implementation as simple as possible. What is your policy?

Display multiple markers and get information from the same API no matter which marker is clicked. (Register the function to fetch in the event handler.)
After a marker is clicked and a fetch is started, we want to cancel the previously started fetch before another marker is clicked and another fetch is started.
I would prefer to use AbortController for the standard function.
I would like to make the implementation as simple as possible. What is your policy?

Hook construction of objects

I am trying to intercept the construction of all objects.

function inhertFrom(){
 this.property = 'Example'
}

let inhertedObject = new inhertFrom()

Whenever there’s ant case of construction on an object, I want to intercept it and console.log(${object} was constructed as example..)

Is there any way to do it?

CSP frame-ancestors self directive blocks page served from same origin

I have a nodejs app which serves
index.html for “/” route
test.html for “/test” route

app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname + "/index.html"));
});

app.get("/test", (req, res) => {
  res.sendFile(path.join(__dirname + "/test.html"));
});

index.html has an iframe which embeds /test as below

   <iframe
        width="100%"
        height="500px"
        src="http://localhost:5500/test"
        sandbox
      ></iframe>

In server.js, I am applying CSP as below:

app.use(function (req, res, next) {
  res.setHeader("Content-Security-Policy", "frame-ancestors self");
  next();
});

The content from /test route is blocked by Chrome saying
enter image description here

As per MDN for frame-ancestors,
enter image description here

The URL scheme and port are same for both are same i.e. http://localhost:5500

Host:
enter image description here

Content being iframed can be access independently:
enter image description here

Why is http://localhost:5500/test not being considered as sameorigin when compared to http://localhost:5500?

Minimal reproducible example – https://github.com/phalgunv/csp-demo-same-origin

Coloring keywords in CSS

I am a backend developer, and I know only basics of frontend.

I am currently working on a blog website, where I want to show codes, and I want the keywords to be properly colored.

Is there any property in CSS or Javascript, that I can use to color specific words?

I tried searching for some CSS property that will allow me to color specific patterns, but couldn’t find any such thing on popular web-dev sites.

Socket.io w/ Cluster Adapter – How to customize rooms and send information to client?

I’m trying to make a visual game lobby where it shows the name, type, current player count, and max player count – and send all the available rooms to the clients. I’ve tried io.sockets.adapter.rooms, but this returns only what’s inside it’s own cluster, not the others. I’ve also tried io.fetchSockets( ), but this just returns the names of the rooms.

I want the client to customize a room (e.g give it a type, a name, max users, ect) and for the room to keep this information, and send to clients on request (just like most games)

Client

socket.emit( 'refreshLobbiesQuery' );

function createLobby( ) {
    const lobbyInfo = {
        name: 'Test',
        type: 'RPG',
        maxUsers: 10
    }

    socket.emit( 'createLobby', lobbyInfo );
}

Server

socket.on( 'createLobby', ( data ) => {
    try {
        socket.join( data.name );
        
        // Edit room data?
        room.data = {
            name: data.name,
            type: data.type,
            currentUsers: getCurrentUsers( room.name ),
            maxUsers: data.maxUsers
        }
    }
    catch( e ) {
        console.log( e );
    }
} );
socket.on( 'refreshLobbiesQuery', ( data ) => {
    socket.emit( 'refreshLobbiesServer', listOfAvailableLobbiesWithInfo );
} );

trying to implement turnjs into blazor wasm but i fail

I am trying to use turnjs with blazor wasm to create a flipbook.
I have the following problem.
If i place the turnjs div container under index.html it works.
enter image description here

But the moment i try to move the div into a foreach inside a component this does not work anymore.
enter image description here

This is the exception i get inside google chrome once i move the container inside a component.
enter image description here

I believe it has something to do with the following javascript method, maybe i also have to move it out from the index.html when i add the container to a component.
enter image description here

Any body has any experience with turn js and blazor?

hi guys i am making some school projects and i need help why my tepmplates is white [closed]

enter image description here
i need help

i try to make tepmplate and this doesnt work i am working on my school project…………………………………………………………………………………………………………………………………………………………………,,.,,.,.,.,.,.,.,.,.,.,………………………………………………………………………………………………………………………………………………………..
asfnaskfnsapfnosanfsanfasklfnsalfnsaflsaflsafnsaflkafasnklsanfnlsafknklsfnlkfsaksfkasnfffffffffffffffffffffffffffffffffffffflllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll

App width exceeds 100% displaying a horizontal scrollbar even when width is set at 100vw for all parent containers

I have created my portfolio website at Portfolio.
I have used styled components for css and below is my App.jsx code

App.jsx:

import './App.css';
import styled from 'styled-components';
import Navbar from './components/Navbar';
import Hero from './components/Hero';
import About from './components/About';
import Work from './components/Work';
import Contact from './components/Contact';
import Particle from './components/Particle';

const Container = styled.div`
  width: 100vw;
  height: 100vh;
  /* overflow: hidden; */
  scroll-snap-type: y mandatory;
  scroll-behavior: smooth;
  scrollbar-width: none;
  color: white;
  &::-webkit-scrollbar {
    display: none;
  }
`;

function App() {
  return (
    <Container>
      <Particle></Particle>
      <Navbar></Navbar>
      <Hero></Hero>
      <About></About>
      <Work></Work>
      <Contact></Contact>
    </Container>
  );
}

export default App;

I am unable to remove the horizontal scroll that appears on the page and fit the content so that it occupies 100% width on any given screen.

I have tried applying width: 100vw to all the parent components including html and body but to no avail. If you open the above link you’ll see that there is a horizontal scroll which prevents the app from being responsive on all screen sizes. I am not that good with CSS yet I have gone through several StackOverflow articles and other sites to modify my CSS to make this work.

Also for anyone wondering about the overflow:auto property that can be used, that won’t work because I have used an npm package react-scroll to apply smooth scrolling effect to all my sections on the website and using the overflow:auto property prevents the react-scroll package from working correctly so I cannot use the overflow property. Can anyone help me remove the horizontal scroll that appears on the page so that my content correctly occupies 100% of the screen and not exceed it.

There’s also a possibility that some other component or CSS is causing this issue hence I have also included the GitHub link for the same as I do not want to spam the post by including the entire project code.

Here’s the GitHub link for the project I have created if you need to look at any other files from the project: code repo for portfolio

Apart from this if you require any other info I would be willing to edit this post to help better understand the question.

how do I make my webpage look the same on bigger screens as on smaller screens?

My website is made for/on a 1366px monitor and on any thing less wide it looks good.
But on anything that is bigger 1366px it becomes stretched out and the footer becomes visible and I rather not have it be visible.
The easy solution is to have a popup on bigger screens asking you to zoom in but not it’s not a very user friendly.

Here are some example images:

On the ideal screen:
shows website on ideal screen size

On a bigger than ideal screen:
shows the footer and that the webpage is spread out to much
(note I zoomed out to simulate how it would display on a higher resolution screen)

on a phone:
shows a my website on a phone screen

here is the link to my website if necessary: minimos11.net

I have tried to change every thing that used pixels to vh or vw but that didn’t seem to go so well.
Have also tried to change the viewport width=device-width to width=1366px but that does not work.
I have also used max-with but does not help with the footer problem and then there is also a white space need fill with a image.

How do I correctly reference gpu-browser.js?

This might sound like a stupid question but anyways; When I try to reference the gpu-browser.js file in my html it doesn’t affect my other scripts. Its as if I never put it in, when I try to do the code snippet provided in the documentation it gives me this error:
Uncaught TypeError: GPU is not a constructor

Specifically my code looks like this:

    <script src="node_modules/gpu.js/dist/gpu-browser.min.js"></script>
    <script>
        // GPU is a constructor and namespace for browser
        const gpu = new GPU();
        const multiplyMatrix = gpu.createKernel(function(a, b) {
            let sum = 0;
            for (let i = 0; i < 512; i++) {
                sum += a[this.thread.y][i] * b[i][this.thread.x];
            }
            return sum;
        }).setOutput([512, 512]);
    
        const c = multiplyMatrix(a, b);
    </script>

I installed gpu.js with npm –save and am using Python version 3.11.

Passed array into component doesn’t update in the component. react

I have an array that stores components that are being rendered on the page. Each of those components needs to have access to this array so Im passing the array into them like usual however when I update the array, arrays inside of the components stay the same can any one help me out a little what is going on?

Parent of the components:

export default function Page({}: Props) {
  const [elements, setElements] = useState<ReactNode[]>([]);

  return (
    <main className="defaults contain pt-[10vh]">
      <textarea placeholder="Title" className="w-full title" />

      <div className="w-full space-y-2">
        {elements.map((element, index) => element)}
      </div>

      <button
        className="block"
        onClick={() => {
          setElements((prev) => [
            ...prev,
            <EditElement draggableElements={elements} key={prev.length} />,
          ]);
        }}
      >
        +
      </button>
      <button>Publish</button>
    </main>
  );
}

Update: The problem has nothing to do with rendering components, when I console.log(elements) from within the EditElement it gives me a value of elements at the moment of EditElement elements creation and doesn’t update it that’s the problem.

Need Help Creating a Chrome Extension to Replace API Response with 504 Status Code

Here’s a revised version of your post for Stack Overflow:

Title: Need Help Creating a Chrome Extension to Replace API Response with 504 Status Code

Hello Stack Overflow community,

I’m trying to create a Chrome extension that replaces an API response with a 504 status code. I’m aware that the extension “requestly” can achieve this, but I want to create my own extension tailored for a specific call.

I attempted to solve this using ChatGpt queryly, but the solution provided didn’t work. I’d appreciate any guidance or suggestions from those who have experience with this.

Here’s what I have so far:

Manifest:


{
  "manifest_version": 3,
  "name": "Fake Status Code",
  "version": "1.0",
  "background": {
    "service_worker": "background.js"
  },
  "permissions": ["webRequest", "webRequestBlocking"]
}

Background Script:


chrome.webRequest.onHeadersReceived.addListener(
  function(details) {
    if (details.url.includes('bet365.com/streamingapi/v2/stream')) {
      return {responseHeaders: [{name: 'Status', value: '504 Gateway Timeout'}]};
    }
  },
  {urls: ["<all_urls>"]},
  ["blocking", "responseHeaders"]
);

Any help would be greatly appreciated. Thank you!

Changing text of a date with JS

I’m wanting to change a basic custom text field for wordpress, example is:

“Draw Date: Sun 17th Sept” with the div class of “draw-date-single”

I’ve been trying this javascript code, at the closing body tag,

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Get the div element with the class "draw-date-single"
    const divElement = document.querySelector('.draw-date-single');

    // Check if the element exists before attempting to modify it
    if (divElement) {
        // Get the content of the div
        const content = divElement.textContent.trim();

        // Create a date string for today in the same format
        const today = new Date().toLocaleDateString('en-US', {
            weekday: 'short',
            day: 'numeric',
            month: 'short',
        });

        // Create a date string for tomorrow
        const tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate() + 1);
        const tomorrowFormatted = tomorrow.toLocaleDateString('en-US', {
            weekday: 'short',
            day: 'numeric',
            month: 'short',
        });

        // Check if the content matches today or tomorrow and update the div content
        if (content === today) {
            divElement.textContent = 'Today';
        } else if (content === tomorrowFormatted) {
            divElement.textContent = 'Tomorrow';
        }
    }
});
</script>

Basically want to change it so if the date states in the div “Draw Date: Sun 17th Sept”

on the 16th Sept it’ll change to “Draw Date: Tomorrow” and the day of 17th it’ll say “Draw date: Today”

Thanks in adavnced

jsx script for analyze the opened active images is horizontal & vertical then open the psd layer path then insert the correct images in correct layers

Need a jsx script for analyze the opened active images is horizontal & vertical then open the PSD layer path then insert the correct images in correct layers

I am new in development and I want a jsx script for analyze the opened active images is horizontal & vertical then open the PSD layer path then insert the correct images in correct layers..

Why does .limit() result empty array when using a query object as a parameter?

I am setting up a mongoose query where I would like to find specific records, mentioned in a custom queryObject. This queryObject contains the key-value pairs, if existent. So, if the res.query does not contain the e.g. limit, it is not added to the queryObject.

For whatever reason, the queryObject.limit parameter results in an empty array. It does filter, when entering a variable that has a number assigned, though.

This does NOT work:

const showOneMovie = async(req,res)=>{
    try {
        const {title, publishDate, genre, skip, sort} = req.query;
        const queryObject = {};
        if(title){
            queryObject.title = title;
        }
        if(publishDate){
            queryObject.publishDate = publishDate;
        }
        if(sort){
            sort === "Ascending" ? queryObject.sort = "-title" : queryObject.sort = "title";
        }
        queryObject.limit = 2;
        let data = await Movie.find(queryObject).limit(queryObject.limit);
        res.status(200).json(data);
    } catch (error) {
        console.log(error)
    }
}

This works:

const showOneMovie = async(req,res)=>{
    try {
        const {title, publishDate, genre, skip, sort} = req.query;
        const queryObject = {};
        if(title){
            queryObject.title = title;
        }
        if(publishDate){
            queryObject.publishDate = publishDate;
        }
        if(sort){
            sort === "Ascending" ? queryObject.sort = "-title" : queryObject.sort = "title";
        }
        const limit = 2;
        let data = await Movie.find(queryObject).limit(limit);
        res.status(200).json(data);
    } catch (error) {
        console.log(error)
    }
}

I know I could skip this issue, but I would really like to understand that behaviour.