is there a way to create a scrollfunction for specific timestamps in a video?

I have this scroll effect where its playing through the video on scroll. But is there a way to make it so when I scroll it scrolls down to specific time parts, and then stop on each? to create a “slideshow feel”. right now I’m using scrollmagic to achieve what I have.

The code for how it works now:

   <div className="intro bg-black">
        <h1 className="uppercase text-center text-white text-5xl">We Present Our New App<span className="text-rose-300">.</span></h1>
        <div className="bounce">
        <i className="fa-solid fa-circle-arrow-down scrollDown text-rose-300 text-5xl"></i>
        </div>
        <video className="appVideo" muted={true} preload="auto" src={video}></video>
    </div>

           const intro = document.querySelector('.intro');
           const introVideo = document.querySelector('.appVideo');


           // Scrollmagic controller
           const controller = new ScrollMagic.Controller();
           
           let scene =  new ScrollMagic.Scene({
       
               duration: 53000, // length of video in ms
               triggerElement: intro,
               triggerHook: 0
           })
           .setPin(intro)
           .addTo(controller);


           // Video Animation
           let accelamount = 0.1;
           let scrollpos = 0;
           let delay = 0;
       
       
           scene.on('update', e =>{
               scrollpos = e.scrollPos / 1000;  
           });
           
           // Makes the video not stop imideatly when you stop scrolling for smoother experience.
           setInterval(() => {
               delay += (scrollpos - delay) * accelamount;
               introVideo.currentTime = delay; 
           }, 33.33);

Document.referrer is empty after redirect

I have a service A that, when reaching it with url www.y.com returns a 302 redirect with Location header, with url www.x.com.
When I go to www.y.com, I get a redirect to www.x.com, but when in console I check document.referrer I see an empty referrer.
I tried to add Referer header or Referrer-Policy header but could not make document.referrer to return www.y.com

I have control on service A and domain www.x.com

Storing SVG settings in a global variable to retain its contents during resize – acceptable?

In the solution I’ve been asked to maintain, there are several responsive SVG charts. When the page is loaded, settings for each chart are stored using the following:

  <input type='text' id='chartA' style='display:none' value='{{settingsChartA}}'>

Then, when the window is resized, there is no current view so the data SVG data are loaded from this value:

if (Blaze.currentView && Template.currentData()) {
        let currentData = Template.currentData();
        if (currentData) {
            settings = ....
        }
    } else {  //WHEN THERE IS NO VIEW, USED STORED DATA
        let s = $('#chartA').val();
        if (s) {
            settings = JSON.parse(s);
        }
    }
    return settings;

I’m now wondering, why not use a global variable, isnt it much simpler? It would be set and read the same way as the input field above. Am I missing some obvious drawback / issues?

How to Play External Audio Files Violating Content Security Policy Directive in a Chrome Extension?

I am developing a Chrome extension that enables users to send selected text to a server, which then converts it into speech and returns an MP3 URL for playback.

However, on certain websites, I encounter a Content Security Policy error, preventing the loading and playback of the MP3 URL. The error message is as follows:

Refused to load media from 'https://storage.googleapis.com/***8d7fc.mp3' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'media-src' was not explicitly set, so 'default-src' is used as a fallback.

Given this situation, how can I successfully play audio files stored on an external server that violate the Content Security Policy directive?

What I have tried:

I attempted to overwrite the meta tag, but the error remains unresolved. I presume this is because the header information takes precedence. Here is the meta tag I used:

<meta http-equiv="Content-Security-Policy" content="default-src 'self'; img-src *; media-src *; font-src *; style-src *">

Any suggestions or solutions would be greatly appreciated.

JavaScript IntersectionObserver Incorrect Behaviour with DOM Layout changes

Expected Behaviour: IntersectionObserver must correctly report the observed component’s visibility in the viewport.
Current Behaviour: IntersectionObserver incorrectly reports component as invisible despite being in the viewport when another component is dragged and dropped to change the DOM layout.

enter image description here

My useOnScreen hook –

// intersection observer is buggy with golden layout
// move C component and keep all in view, but B component will be marked not on screen
function useOnScreen(label, ref) {
  const [isOnScreen, setIsOnScreen] = useState(false);
  const observerRef = useRef(null);

  useEffect(() => {
    observerRef.current = new IntersectionObserver(
      ([entry]) => {
        setIsOnScreen(entry.isIntersecting);
      },
      { root: document.body }
    );
  }, []);

  useEffect(() => {
    observerRef.current.observe(ref.current);

    return () => {
      observerRef.current.disconnect();
    };
  }, [ref]);

  return isOnScreen;
}

How I use this hook in my React component –

const Text = ({ label }) => {
  const ref = useRef(null);
  const onScreen = useOnScreen(label, ref);
  useEffect(() => {
    if (onScreen) {
      console.log("onscreen", label);
      return () => {
        console.log("not on screen", label);
      };
    }
  }, [onScreen, label]);

  return <h1 ref={ref}>{label}</h1>;
};

Demo Video of the bug: https://drive.google.com/file/d/1W54-D3BT7FNqZNS4EzBDYdJFqdHD-iCx/view?usp=sharing

Code Setup for the bug: https://codesandbox.io/s/golden-layout-react-intersection-observer-zhnq3c?file=/src/App.js:289-615


My Approach

  • I noticed that rootBounds.width and rootBounds.height are 0 in the IntersectionObserverEntry for component B when DOM layout is changed on drag/drop of component C.
  • Hence, it feels component B is not in view because the viewport is of 0 size
  • I even tried with passing options.root = document.body while creating the IntersectionObserver in its constructor but still same issue.
  • If I chose to ignore the callback when rootBounds is of 0 size, I will then miss legit cases where a component B is not in viewport but the hook will still keep it as visible.
  • The next solution I think is to hook into GoldenLayout events to track which tabs are active and which are not and pass that prop to my Components somehow.
  • Is there a better solution here?

Why search doesn’t work properly with infinite scrolling

please tell me what can be done to save “infinite scrolling” and at the same time so that the search works correctly.

Description of the problem:

I have an array with elements ( filteredPizzas ). I get this array in the Home component and pass it to the PizzaList component already with a certain length by using slice ( it just my implementation of infinite scrolling without API requests )

In the PizzaList component, I filter the passed array by the searchValue and then just display the cards.

The problem is that if the user DOES NOT scroll the page and starts entering the name of some element, it will not be displayed, but this element is definitely in the array it just hasn’t been loaded yet by “infinite scrolling”.

App component:

const App = () => {
    const [pizzas, setPizzas] = React.useState<Array<Pizza>>([]);
    const [filteredPizzas, setFilteredPizzas] = React.useState<Array<Pizza>>([]);
    const [selectedCategorie, setSelectedCategorie] = React.useState<number | null>(parseJSON(CATEGORIE_KEY));
    const [cart, setCart] = React.useState<Array<Cart>>(parseJSON(CART_KEY) ?? []);
    const [currentSort, setCurrentSort] = React.useState<number>(parseJSON(SORT_INDEX_KEY) ?? 0);
    const [searchValue, setSearchValue] = React.useState("");
    const [loading, setLoading] = React.useState<boolean>(true);
    const [errorData, setErrorData] = React.useState<Error | unknown>(null);

    React.useEffect(() => {
        (async () => {
            try {
                const { data } = await api.getPizzas();
                const sortDirection = initialSortNames[currentSort].sort.includes("-") ? -1 : 1;

                setPizzas(data);
                setFilteredPizzas(
                    (typeof selectedCategorie === "number"
                        ? data.filter(({ category }) => category === selectedCategorie)
                        : data
                    ).sort((a, b) => {
                        const sortProperty = initialSortNames[currentSort].sort.replace("-", "");
                        return (
                            (Number(a[sortProperty as keyof Pizza]) - Number(b[sortProperty as keyof Pizza])) *
                            sortDirection
                        );
                    })
                );
            } catch (error) {
                console.error(error);
                setErrorData(error);
            } finally {
                setLoading(false);
            }
        })();
    }, []);

    React.useEffect(() => saveToLocalStorage({ key: CART_KEY, data: JSON.stringify(cart) }), [cart]);

    if (errorData || (!loading && !pizzas.length)) {
        return (
            <NotFound
                title='Cannot get data from the server'
                description='Please, check your internet connection and refresh the page'
                reloadButton
                reloadButtonText="Refresh Page"
                screen
                code={errorData}
            />
        );
    }

    return loading ? (
        <Spinner />
    ) : (
        <AppContext.Provider
            value={{
                loading,
                errorData,
                pizzas,
                filteredPizzas,
                setFilteredPizzas,
                setPizzas,
                cart,
                setCart,
                selectedCategorie,
                setSelectedCategorie,
                currentSort,
                setCurrentSort,
                searchValue,
                setSearchValue,
            }}
        >
            <Routing />
        </AppContext.Provider>
    );
};

export default App;

Home component:

const Home = () => {
    const { filteredPizzas } = React.useContext(AppContext);

    const [view, setView] = React.useState(6);

    const handleScroll = () => {
        if (document.documentElement.scrollHeight - (document.documentElement.scrollTop + window.innerHeight) < 100 && view < filteredPizzas.length) {
            setView((prevState) => prevState + 3);
        }
    };

    React.useEffect(() => {
        document.addEventListener("scroll", handleScroll);

        return () => document.removeEventListener("scroll", handleScroll);
    }, [view, filteredPizzas]);

    return (
        <section>
            <Container>
                <div className="flex flex-col gap-5">
                    <Tools categories={initialCategories} sortNames={initialSortNames} />
                    <Title title="All Pizzas" />
                </div>
                <PizzaList data={filteredPizzas.slice(0, view)} />
            </Container>
        </section>
    );
};

export default Home;

PizzaList component:

const PizzaList: React.FC<Props> = ({ data }) => {
    const { searchValue } = React.useContext(AppContext);

    const isEmpty = !data.filter(({ title }) => title.toLowerCase().includes(searchValue.toLowerCase())).length;

    return (
        <ul className='py-[30px] flex flex-wrap justify-between items-center gap-10'>
            {isEmpty ? (
                <Title title={`${searchValue} not found`} />
            ) : (
                data
                    .filter(({ title }) => title.toLowerCase().includes(searchValue.toLowerCase()))
                    .map((item) => (
                        <li key={item.id}>
                            <Card {...item} />
                        </li>
                    ))
            )}
        </ul>
    );
};

export default PizzaList;

Search component:

const Search = () => {
    const { setSearchValue } = React.useContext(AppContext);

    const [value, setValue] = React.useState("");

    const handleChange = ({ target: { value } }: React.ChangeEvent<HTMLInputElement>) => {
        setValue(value);
        handleDelay(value);
    };

    // eslint-disable-next-line react-hooks/exhaustive-deps
    const handleDelay = React.useCallback(debounce((value: string) => setSearchValue(value)), []);

    const handleClear = () => {
        setValue('');
        setSearchValue('');
    }

    return (
        <form className='basis-[300px] relative'>
            <Input
                classNames='border outline-none focus:border-primary-orange border-solid border-primary-gray py-[5px] px-[40px] box-border rounded-lg w-full'
                type='text'
                value={value}
                onChange={handleChange}
                placeholder='Search...'
            />
            <button title='search' type='button' className='absolute left-2 top-[50%] translate-y-[-50%]'>
                <img src={getImageUrl("search.svg")} alt='search icon' />
            </button>
            {!!value && (
                <button onClick={handleClear} title='clear' type='button' className='absolute right-3 top-[50%] translate-y-[-50%]'>
                    <img src={getImageUrl("clear.svg")} alt='search icon' width={12} height={12} />
                </button>
            )}
        </form>
    );
};

export default Search;

error TypeError: Cannot read properties of undefined (reading ‘headers’) with nextjs [duplicate]

I have an app router setup with the code below. When calling the endpoint, i get Internal Server Error: 500, with the error log on server error TypeError: Cannot read properties of undefined (reading 'headers') at eval (webpack-internal:///(rsc)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:266:61)

import { NextRequest, NextResponse } from 'next/server';

// Import and initialize your gRPC client here
const grpc = require('@grpc/grpc-js');
const protoLoader = require('@grpc/proto-loader');

var PROTO_PATH = __dirname + '/../myproto.proto';

try {
  var packageDefinition = protoLoader.loadSync(PROTO_PATH, {
    keepCase: true,
    longs: String,
    enums: String,
    defaults: true,
    oneofs: true
  });
} catch (error) {
  console.error('Error loading proto file:', error);
}

var qProto = grpc.loadPackageDefinition(packageDefinition).myproto;

var client = new qProto.QEngine('localhost:6767', grpc.credentials.createInsecure())

export async function POST(req: Request, res: Response) {
  try {
    const body = await req.json()
    var reqq = qProto.QueryRequest;

    reqq.query_string = body.queryString
    reqq.debug = body.debug;

    // Make the gRPC query call using your gRPC client
    client.Query(reqq, function(err: Error, grpcResponse: any) {
      // console.log('gRPC Response:', JSON.stringify(grpcResponse, null, 2));
      if (err) {
        console.error('Error calling Query:', err);
        return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
      } else {
        // Set the status code and send the response directly using res.json
        return NextResponse.json({ data: grpcResponse }, { status: 200 })
      }
    });
  } catch (error) {
    console.error('Error:', error);
    return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 })
  }
}

on investigating my breakpoints, i see that as soon as client.Query() is called, a 500 error is returned (testing with postman), without waiting to reach either of the return statements. I am able to see the grpcResponse being populated correctly. Not sure what’s causing it to return early.

using nextjs and testing code locally on vscode.

Getting Babel error when compiling build with Create React App

For my web app I used Create React App to build it with the typescript template. I am about ready to deploy but I am unable to create a production build with npm run build. Because of the following Babel error:

src/constants/{file-name}.js
  Line 0:  Parsing error: You appear to be using a native ECMAScript module configuration file, which is only supported when running Babel asynchronously

This happens for every file I use to store constant values which are used across my web app. I have tried a lot of things such as refactoring them into .json files and changing my babel config file to .cjs but nothing seems to work. I don’t really get why Babel has such a problem with me using exported values from other files since I use functions from other files.

babel.config.js:

module.exports = function (api) {
    return {
      plugins: ['macros'],
    }
  }

package.json:

{
  "name": "front-end",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/react": "^11.11.0",
    "@emotion/styled": "^11.11.0",
    "@fortawesome/fontawesome-svg-core": "^6.4.0",
    "@fortawesome/free-regular-svg-icons": "^6.4.0",
    "@fortawesome/free-solid-svg-icons": "^6.4.0",
    "@fortawesome/react-fontawesome": "^0.2.0",
    "@metamask/sdk": "^0.4",
    "@mui/icons-material": "^5.11.16",
    "@mui/material": "^5.13.4",
    "@mui/x-data-grid": "^6.9.2",
    "@prisma/client": "^5.0.0",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "@types/jest": "^27.5.2",
    "@types/node": "^16.18.34",
    "@types/react": "^18.2.8",
    "@types/react-dom": "^18.2.4",
    "@types/styled-components": "^5.1.26",
    "@typescript-eslint/parser": "^5.59.8",
    "babel-plugin-macros": "^3.1.0",
    "bootstrap": "^5.3.0",
    "emoji-picker-react": "^4.4.11",
    "eslint": "^8.42.0",
    "ethers": "^6.6.7",
    "express": "^4.18.2",
    "prompt-sync": "^4.2.0",
    "rate-limiter-flexible": "^2.4.2",
    "react": "^18.2.0",
    "react-bootstrap": "^2.7.4",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.15.0",
    "react-scripts": "5.0.1",
    "socket.io": "^4.7.1",
    "styled-components": "^5.3.10",
    "ts-node": "^10.9.1",
    "typescript": "^5.0.1",
    "web-vitals": "^2.1.4",
    "web3": "^4.0.3"
  },
  "overrides": {
    "typescript": "^5.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "prettier": "2.8.8",
    "prisma": "^5.0.0",
    "ts-node": "^10.9.1"
  },
  "type": "module"
}

how to disable submitt button when Username already exist in database

I am checking duplicate entry issue in my form with javascript, for example : When I entered duplicate username then its creating message that user already exist . (everything working fine till this ) But when I click submit, its also entered data into database by ignoring existing message, how can I stop submit button from processing if duplicate message is display before submit button. here is my code main file

<html>
<head>
<script src="http://code.jquery.com/jquery-3.3.1.js"></script>
</head>
<body>
<form class="a16" action="form9.php" method="POST" autocomplete="on">
                                    <label for="userName" class=" ">Użytkownik:</label>

<input type="text" name="userName" placeholder="Username" id="userName1" onBlur="checkAvailability()">

      <span id="user-availability-status"></span> 
<p><img src="LoaderIcon.gif" id="loaderIcon" style="display:none" /></p>

<input type="submit" name="submit" id="submit" value="Submit">

 <script type="text/javascript">     

function checkAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "proceser.php",
data:'userName='+$("#userName1").val(),
type: "POST",
success:function(data){
$("#user-availability-status").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
</script>

and here is proceser.php

<?php
 include 'db1.php';   //standard datebase local connection..

 if(isset($_POST['userName']) && $_POST['userName']!="") {
     if ($stmt = $con->prepare('SELECT userName FROM ttt WHERE userName = ?')) {
         $stmt->bind_param('s', $_POST['userName']);
         $stmt->execute();
         $stmt->store_result();
         $numRows = $stmt->num_rows;
         if ($numRows > 0) {
             echo "<span class=''> Username Not Available.</span>";
         } else {
             echo "<span class=''> Username Available.</span>";
         }
     }
 }
$con->close();
ob_end_flush();

?>

and in the end here is form9.php which do processing of database

<?php
    // getting all values from the HTML form
    if(isset($_POST['submit']))
    {
        $username1 = $_POST['userName'];

    }       

    // database details
    $host = "localhost";
    $username = "root";
    $password = "";
    $dbname = "hmis";

    // creating a connection
    $con = mysqli_connect($host, $username, $password, $dbname);

    // to ensure that the connection is made
    if (!$con)
    {
        die("Connection failed!" . mysqli_connect_error());
    }

    // using sql to create a data entry query
    $sql = "INSERT INTO ttt (username)
 VALUES ('$username1')"; 

   
  
    // send query to the database to add values and confirm if successful
    $rs = mysqli_query($con, $sql);
    if($rs)
    {
        echo "";
    }

I am getting a JSLint insecure exception error when trying to validate a password in JavaScript

while trying to validate the password with regular expression in the .js file I am getting the error as** Run JSLint (if jslint.scan.dir=/src/…) Failed**
this happens while building the application
got the following exception–>
Insecure ‘.’.
var passw= /^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[@$!%*?&])[A-Za-zd@$!%*?&]{8,}$/;
^

passwordPatternCheck : function passwordPatternCheck(){
                           var patternCheck = function passPatternCheck(submittedValues, validation) {
                               var result = null;
                               var submitted = submittedValues[validation.name];
                               var passw= /^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[@$!%*?&])[A-Za-zd@$!%*?&]{8,}$/;
                               if (submitted && !submitted.match(passw)) {
                                   var displayName = validation.label || validation.name;
                                   result = i18n("Should have 8 or more characters with atlease one uppercase, one lowercase, one number and one special character as %s.", displayName);
                               }
                               return result;
                           };
                           return patternCheck;
            },

tried to escape the dot[.] but the regex is not working as expected
(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[@$!%*?&])[A-Za-zd@$!%*?&]{8,}$

How do I make a button change a certain value in my javascript application?

I’m creating a application using JS and HTML and was wondering how to implement a button that will update a value with the parameters of three items to choose from.

Here was I got so far:

**This is how the “value” is displayed in html – **

<div id="md" class="mdtxt">{mode}</div>

**Using the following script to automatically update the value from default through js – **

<script> document.getElementById("md").innerHTML = currentMode; </script>

**Here is the js side of things – **

script.js will let currentMode = null; (is nulled to demostrate default)

config.js defines modes as config.zones = [ { modeid: 1, modetag: "Mode #1", }, { modeid: 2, modetag: "Mode #2", }, { modeid: 3, modetag: "Mode #3", }, ]

Hopefully I gave a good understanding, now I want my html button to be able to cycle through the modes and then wrap back around to the first one in a continuous cycle.

I have a html button element with a id so the element would be id="btns1"

I’ve tried to use some code from a previous project, as well as watch so youtube tutorials but nothing seems to be helping me understand this.

How to make Monaco editor show n or ” in the editor

I have the following problem, I want Monaco editor to literally show me the characters as I passed them in the value, to show n and . But it couldn’t, any suggestions?

this is my code

editor_source = monaco.editor.create(document.getElementById('editor_source'), {
    value: "{n  "message": "¡Hello World!", n  "status": "successful"n}",
    language: 'plaintext',
    wordWrap: 'on',
    tabSize: 2,
    indentSize: 2,
  })

This is what it looks like in the editor

{
  "message": "¡Hello World!", 
  "status": "successful"
}

monaco-editor

and I want it to show like this

{n  "message": "¡Hello World!", n  "status": "successful"n}

thank you very much for your help

rewind youtube embedded video [html, css, js]

I’m new to the whole html css js pack and I’m trying to create a website that will display a youtube video with the controls locked (I’ve done this by blocking the user from interacting with the video) and I want to add some rewind and slow down buttons The video is inside an iframe

<div class="video-background"> <div class="video-foreground"> <iframe id="myvid" class="ytplayer-nbvz" src="" frameborder="0" allowfullscreen loading="lazy" controls="0" ></iframe> </div> </div>

I’ve tried using Youtube’s API and queryselector, I tried queryselector on the iframe element and worked (the console log printed the iframe) but when I attempted .playbackRate it didn’t change anything