How to open and read a json file on a server-hosted and local html file

Using HTML, CSS, and JS I have written a word chain game that uses JSON files to store game data for the many rounds of a single game. I wish to make it fairly user-friendly, so I want to make it possible to drag and drop the file onto the game window. I get a CORS error when running the HTML locally as one expects (it worked with --disable-web-security set). However, I get an error when running the game from the server:

Not allowed to load local resource: file:///C:/fakepath/<filename>.json

The HTML is very simple:

<input type="file" name="gameData" id="gameData"><button id="loadGame">Load Game</button><br><br>

The JS is the problem, I’m sure:

$("#loadGame").on("click", function() { // Load the game file, however it needs to be in the game directory to work!
    var filePath = $("#gameData").val().replace(/^.*[\/]/, '');
    // var filePath = $("#gameData").val();  // Version for online only game, maybe....
    consoleWrite(`File "${filePath}" loaded from game directory.`);
    $.getJSON(filePath, function(data) {
        round1 = data.round1;
        consoleWrite(`Round 1: ${round1}`);
        round2 = data.round2;
        consoleWrite(`Round 2: ${round2}`);
        round3 = data.round3;
        consoleWrite(`Round 3: ${round3}`);
        round4 = data.round4;
        consoleWrite(`Round 4: ${round4}`);

        extraRound1 = data.extraRound1;
        consoleWrite(`Extra 1: ${extraRound1}`);
        extraRound2 = data.extraRound2;
        consoleWrite(`Extra 2: ${extraRound2}`);
        extraRound3 = data.extraRound3;
        consoleWrite(`Extra 3: ${extraRound3}`);

        bonusRoundA = data.bonusRoundA;
        consoleWrite(`Bonus A: ${bonusRoundA}`);
        bonusRoundB = data.bonusRoundB;
        consoleWrite(`Bonus B: ${bonusRoundB}`);
        bonusRoundC = data.bonusRoundC;
        consoleWrite(`Bonus C: ${bonusRoundC}`);
    });
    consoleWrite(`Game loaded.`);
});

What must I change to allow the game to parse the file? Is there any way to read the file’s contents locally without uploading it to a server? I’d like it to be able to work locally and hosted on a server. The “less-user-friendly” workaround I thought of is to have the user copy and paste the contents of the file into a textbox; I’ve done stuff like that before, and while it works I’d rather keep with a simple file upload option. Any ideas?

DYMO Label Connect JavaScript Library – Barcode issue

I am using the Dymo connect SDK to print labels from our web application.
The customers are designing their labels in the Dymoconnect software (.dymo files) and upload it to our software.

All was working fine but one of our customers started using the barcode object.
It renders fine in print preview, but seems like it’s warped so how as the barcode reader will not read it. If we print directly from Dymoconnect it works fine.

This is an example of how it’s rendered, top is using the SDK, bottom is from the software:

https://i.sstatic.net/M2q7lgpB.png

I thought it might be related to one of the renderParamsXml options, but all documentation points to broken links…

How to locally test sub routes for a basic Javascript router in VSCode live server?

I have an AWS Cloudfront function that redirects urls to several different html pages hosted in S3 along the lines of this:

function handler(event) {
    var request = event.request;
    var uri = request.uri;

    if (uri.split('/')[1] == '') {
        request.uri = '/index.html';
    } else if (uri.split('/')[1] == 'contact'){
        request.uri = '/contact.html';
    } else if (uri.split('/')[1] == 'blog'){
        request.uri = '/blog.html';
    } else if (!uri.includes('.')) {
        request.uri = '/index.html';
    }
    return request;
}

This appears to work fine but I want to build the site locally with my 3 html files in the root directory but have sub routes point to them.

  1. http://127.0.0.1:5500/index.html
  2. http://127.0.0.1:5500/blog/index.html
  3. http://127.0.0.1:5500/contact/index.html

These are the sub routes:

www.example.com
www.example.com/index.html
route to: /index.html

www.example.com/foo
www.example.com/foo/123
www.example.com/foo/abc
www.example.com/foo/def/123
route to: /foo/index.html

www.example.com/bar
www.example.com/bar/123
www.example.com/bar/abc
www.example.com/bar/def/123
route to: /bar/index.html

Effectively I want to be able to use code similar to this to read the pathArray values to change the individual page like blog/hello would show the blog page hello whereas blog would show the blog list:

var pathArray = window.location.pathname.split('/');
document.write("pathArray[0]: " + pathArray[0] + "<br>");   
document.write("pathArray[1]: " + pathArray[1] + "<br>");   
document.write("pathArray[2]: " + pathArray[2] + "<br>");  
document.write("pathArray[3]: " + pathArray[3] + "<br>");   
if (pathArray[3] === undefined) {
    document.write("pathArray[3] === undefined: " + (pathArray[3] === undefined) + "<br>");   
} else {
    document.write("pathArray[3] === undefined: " + (pathArray[3] === undefined) + "<br>");  
}

My HTML is updating correctly to change colour with tailwind, but the browser only actually updates with the colour gray, not other colours, why?

I’m using JS, to update the background colour of an HTML element using tailwind.
It works with the colour gray, but not any other colour.

If I change yellow or green with gray, they update correctly, if I change gray with another colour, it doesn’t work correctly. So, the code is working fine, if I check console, it has the correct tailwind class, it’s just that the browser is not updating the colour displayed, unless it’s gray.

Any ideas why?

It also only updates with 200, so if it’s bg-gray-200 it changes colour, but if it’s anything else, it doesn’t.

Code below:

 for (let i = 0; i < 6; i++) {
            let letterColour = 'yellow'
            let box = row.children[i]
            let letter = currentGuess[i]
            let letterPosition = correctWord.indexOf(currentGuess[i])
            console.log(letterPosition)

            if (letterPosition === -1) {
                letterColour = "gray"
                let colour = "red"
                colourKeyboard(letter, colour)
            }
            else if (currentGuess[i] === correctWord[i]) {
                letterColour = "green"
                let colour = "green"
                colourKeyboard(letter, colour)
            }
 
            let backgroundColour = `bg-${letterColour}-200`
            console.log(backgroundColour)
            box.classList.add(backgroundColour)
            console.log(box)
        }

App is not using routes instead opening 500.ejs directly

Hope you guys doing good.
I am learning Nodejs where i am trying to create login, signup with mongodb

The issue i am getting is the app is directly opening the 500.ejs file instead of route defined. i am using routes, controller and views

The structure of views is views/auth/login,signup views/404.ejs,500.ejs
The structure of Controller is controller/auth.js, error.js
The structure of route is route.auth.js

Here is my app.js code:

const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const MONGODB_URI='mongodb+srv://******:**********@******.majjl.mongodb.net/?retryWrites=true&w=majority&appName=******'
const app = express();


// const multer = require('multer')

// Middleware setup
app.set('view engine', 'ejs'); // Set EJS as the template engine
app.set('views', 'views'); // Set the views directory

app.use(bodyParser.urlencoded({ extended: false })); // Parse incoming request bodies
app.use(express.static(path.join(__dirname, 'public'))); // Serve static files from the public directory

const authRoutes = require('./routes/auth')
const errorController = require('./controllers/error');
// Use authentication routes
app.use(authRoutes);
app.use(errorController.get500);
app.use(errorController.get404);

app.use((err, req, res, next) => {
    res.status(err.httpStatusCode || 500);
    res.render('500', {
    statusCode: err.httpStatusCode || 500,
    message: err.message || 'Something went wrong!'
    });
});



app.get('/', (req, res) => {
    res.redirect('/login');
  });

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

Here is my auth controller:

const User = require('../models/user')
const bcrypt = require('bcryptjs')
const crypto = require('crypto');
const { validationResult } = require('express-validator')
const nodemailer = require('nodemailer')
const sendgrindTransport = require('nodemailer-sendgrid-transport')
const transport = nodemailer.createTransport(sendgrindTransport({
    auth:{
        api_key:"*****************.****************",
    }
}))

exports.getLogin = async (req, res, next) => {
    let message;
    // let message=req.flash('error');
    // if(message.length>0)
    // {
    //     message=message[0]
    // }else{
    // message=null
    // }
    res.render('auth/login', {
        path: '/login',
        pageTitle: 'Login',
        errorMessage: message,
        oldInput : {
            email:'',
        },
    })
}

exports.getSignup = async (req, res, next) => {
    let message;
    // let message=req.flash('error');
    // if(message.length>0)
    // {
    //     message=message[0]
    // }else{
    // message=null
    // }
    res.render('auth/signup', {
        path: '/signup',
        pageTitle: 'Signup',
        errorMessage: message,
        oldInput : {
            fullName:'',
            email:'',
        },
    })
}

Here is my error.js:

exports.get404 = (req, res, next) => {
    res.status(404).render('404', { pageTitle: 'Page Not Found', path: '/404',
       });
  };
  
  exports.get500 = (req, res, next) => {
    res.status(500).render('500', { pageTitle: 'Error', path: '/500',
       });
  };

here is my route/auth.js:

const express = require('express');
const router = express.Router();
const authController = require('../controllers/auth')
const { check, body } = require('express-validator')
const User = require('../models/user')




router.get('/login',authController.getLogin),
router.get('/signup',authController.getSignup),


module.exports = router;

Now when i run the app like npm start the page open and it show 500.ejs with this message:

/Users/mac/development/Private Data/Node Projects/Video-Calling-App/views/500.ejs:6 4| <meta charset="UTF-8"> 5| <meta name="viewport" content="width=device-width, initial-scale=1.0"> >> 6| <title><%= statusCode %> - Error</title> 7| <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> 8| <style> 9| body { statusCode is not defined

Can anyone please help me to solve this also if i comment the error controller it works fine but after open the login page if i go for /login/chujnd it show cannot get login/chujnd but expectedly it has to show 404 page

Event Listeners Not Working After Browser Back Navigation in Laravel Docker Project (bfcache Issue)

I’m working on a Laravel project that’s running in a Dockerized environment with an Apache server. Everything works fine when I navigate the app normally. However, I run into issues when using the browser’s back button.

Specifically, JavaScript event listeners that I have attached on certain DOM elements stop working when I navigate back using the browser’s back button. The problem seems to be related to the browser’s Back-Forward Cache (bfcache), which doesn’t seem to fully reload the page or reattach the event listeners when I navigate back to it.

document.addEventListener('DOMContentLoaded', async () => {
        const connectButton = document.getElementById('connectButton');
        const copyIcon = document.getElementById('copyIcon');

        setupEventListeners();

        if (connectButton) {
            connectButton.addEventListener('click', connect);
        }

        if (copyIcon) {
            copyIcon.addEventListener('click', async () => {
                try {
                    await navigator.clipboard.writeText(getUserWallet());
                    alert('{{ __('trans.navbar.wallet_address_copied') }}');
                } catch (error) {
                    alert('{{ __('trans.navbar.copy_failed') }}');
                }
            });
        }
    });

this is my code it works totally fine when i normally navigate but the listeners doesn’t work when i try to go back to the previous page using browser back. Any Suggestions?

Environment:
Laravel 11 running inside Docker with an Apache server.
Browser: Chrome.
Frontend: Vanilla JavaScript for handling events.

React JS Stop setState batching in async function

I have the react client component, it’s a part of a next.js app, this component is a simple form that sends it’s formData to a next.js server action through an async function that will do the following steps:

  1. Set form button to be disabled & message to “Loading”.
  2. Send formData to Next.JS via an async server action.
  3. Set form button to be enabled & message to error if error.

The problem seems to be that react is batching my setState calls, so in execution it’s as if step 1 doesn’t even happen, just step 2 + 3.

I can’t figure out how to circumvent this behaviour.
Here’s the source code:

"use client";

import { SendGiftAction } from "@/app/actions/SendGiftAction";
import { useState } from "react";

export default function GoldGiftForm()
{
    let [interactable, SetInteractable] = useState(true);
    let [message, setMessage] = useState("");

    async function Execute(data: FormData)
    {
        //These won't change the UI
        SetInteractable(false);
        setMessage("Loading");
        //-------------------------

        //Next.JS Server action
        let response = await SendGiftAction(data);

        //These will change the UI
        SetInteractable(true);
        setMessage(response.Success ? "" : response.Error);
        //------------------------
    }

    return (
        <form action={Execute}>
            <h3>Send Gold Gift</h3>

            <input
                name="userID"
                type="text"
                placeholder="User ID"
            />

            <input
                name="gold"
                type="number"
                placeholder="Gold"
            />

            <button type="submit" disabled={!interactable}> Send Gift </button>

            <p>{message}</p>
        </form>
    );
}

Why callback function passed to promise constructure take 2 functions?

I’m new to Javascript and trying to understand asynchronous mechanism in Javascript.

I learnt that promise good solution for callback problem.

It’s constructor takes a callback function called executer. And the executer function takes 2 function, resolve and reject. The problem for me starts here.

I never define these functions but I use them in executer function. I can’t understand why I pass these two functions to executer. I think these functions are defined in somewhere by the javascript. If it is, why do we not use them like other library functions like map, forEach?

Here is the example code that use promise function created by Microsoft Copilot

function printNumbers2(start, end) {
    return new Promise((resolve, reject) => {
        function printNext(current) {
            if(current > end){
                resolve();
                return;
            }
            console.log(current);
            setTimeout(() => printNext(current + 1), 0);
        }
        printNext(start);
    })
}

i have a blazor app for factory layout and i want to make the functionality of reloading every 15 seconds but it doesn’t work

i’ve tried PeriodicTimer and jsinterop but both doesn’t achieve the desired behaviour

here’s my @code block that outputs no errors, exception nor the expected bahaviour

@code {
public List<Station> Stations = new List<Station>();
private List<Connection> Connections = new List<Connection>();
private List<CurvedConnection> CurvedConnections = new List<CurvedConnection>();
private List<string> LineElements = new List<string>();
private PeriodicTimer periodicTimer;
private CancellationTokenSource _cts = new CancellationTokenSource();
private DateTime currentTime = DateTime.Now;
private bool isInitialized = false;


protected override void OnInitialized()
{
    SetupInitialStations();
    UpdateConnections();
}

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        isInitialized = true;
        periodicTimer = new PeriodicTimer(TimeSpan.FromSeconds(15));

        while (await periodicTimer.WaitForNextTickAsync(_cts.Token))
        {
            await JS.InvokeVoidAsync("reloadPage");
            await JS.InvokeVoidAsync("console.log", "Periodic work done", currentTime);
        }
    }

public void Dispose()
{
    _cts.Cancel();
    periodicTimer?.Dispose();
}}

Virtual list render when scroll is set on parent

I have a problem where I want to use virtual list to render a lot of items, before I used to have scroll on virtual list table element and I would use “scrollTop” to find out how much is scrolled and divide that with height of item in a list to find out index of item in array from which I should render it looked like so:

    const scrolledTop = tableElement.scrollTop;
    const pos = Math.floor(scrolledTop / itemHeight);

So “pos” would have index of item from which to render. this calculation would be done whenever user triggered scrollEvent on “tableElement”

Problem is that now I want to have scroll on parent element instead on table, because parent element has some charts and that table, and I want to be able to scroll through those charts instead of them staying on top. But now I can’t figure out how can I calculate “pos” from which Index I should render item because now “scollTop” property on table element returns 0 when I scroll.

Jest mockResolvedValueOnce method returns undefined when chaining

I am having some issues mocking a Google Analytics client method use Jest. Example A returns undefined within my function. The problem seems to be related to chaining the mockResolvedValueOnce outputs to runReport.

When I format the method as in example B, so just returning a single default value, I do get an output. Why is it that I’m able to return a value when configuring the output within the client, but I’m not able to return anything when configuring the output after the client is initialised?

A.

const { monitorTraffic } = require('../index.js'); 
const { BetaAnalyticsDataClient } = require('@google-analytics/data');
const axios = require('axios');

jest.mock('@google-analytics/data', () => {
  return {
    BetaAnalyticsDataClient: jest.fn().mockImplementation(() => {
      return {
        runReport: jest.fn()
      };
    }),
  };
});

jest.mock('axios');

describe('monitorTraffic', () => {
  let req;
  let res;
  let runReportMock;

  beforeEach(() => {
    req = {}; 

    res = {
      status: jest.fn().mockReturnThis(),
      send: jest.fn()
    };

    const analyticsClientInstance = new BetaAnalyticsDataClient();
    runReportMock = analyticsClientInstance.runReport;

    runReportMock.mockReset();
    axios.post.mockReset();
  });

  it('should send an alert if traffic drops more than the threshold compared to yesterday', async () => {
    runReportMock
      .mockResolvedValueOnce({ rows: [{ dimensionValues: [{ value: '2024-08-30' }], metricValues: [{ value: '100' }] }] })
      .mockResolvedValueOnce({ rows: [{ dimensionValues: [{ value: '2024-08-29' }], metricValues: [{ value: '200' }] }] });

    await monitorTraffic(req, res);

    // Assertions
    expect(runReportMock).toHaveBeenCalledTimes(2); // Ensure runReport is called twice
    expect(res.status).not.toHaveBeenCalledWith(500);
    expect(axios.post).toHaveBeenCalled();
  });

B.

jest.mock('@google-analytics/data', () => {
  return {
    BetaAnalyticsDataClient: jest.fn().mockImplementation(() => {
      return {
        runReport: jest.fn()
          .mockResolvedValue({
            rows: [
              {
                dimensionValues: [{ value: '2024-08-30' }],
                metricValues: [{ value: '100' }]
              }
            ]
          })
      };
    }),
  };
});

Adding the WebWorker to the compiler options in tsconfig.json?

I’ve created a starter template / project for Typescript projects and I’m cloning it down and initializing it like this.

git clone https://github.com/fireflysemantics/fs-typescript-starter fs-highlightjs-worker
cd fs-highlightjs-worker 
npm i
npm run build

And the build runs fine. I want this project to use the Web Worker API and this means that WebWorker has to be added to lib under compilerOptions in tsconfig.json like this:

"lib": ["es2021", "DOM", "DOM.Iterable", "WebWorker"],

However if I do this and run the build it now creates these errors.


node_modules/typescript/lib/lib.dom.d.ts:23:1 - error TS6200: Definitions of the following identifiers conflict with those in another file: ImportExportKind, TableKind, ExportValue, Exports, ImportValue, Imports, ModuleImports, ValueType, name, AlgorithmIdentifier, AllowSharedBufferSource, BigInteger, BinaryData, BlobPart, BodyInit, BufferSource, CSSKeywordish, CSSNumberish, CSSPerspectiveValue, CSSUnparsedSegment, CanvasImageSource, DOMHighResTimeStamp, EpochTimeStamp, EventListenerOrEventListenerObject, FileSystemWriteChunkType, Float32List, FormDataEntryValue, GLbitfield, GLboolean, GLclampf, GLenum, GLfloat, GLint, GLint64, GLintptr, GLsizei, GLsizeiptr, GLuint, GLuint64, HashAlgorithmIdentifier, HeadersInit, IDBValidKey, ImageBitmapSource, Int32List, MessageEventSource, NamedCurve, OffscreenRenderingContext, OnErrorEventHandler, PerformanceEntryList, ReadableStreamController, ReadableStreamReadResult, ReadableStreamReader, ReportList, RequestInfo, TexImageSource, TimerHandler, Transferable, Uint32List, XMLHttpRequestBodyInit, AlphaOption, AvcBitstreamFormat, BinaryType, CSSMathOperator, CSSNumericBaseType, CanvasDirection, CanvasFillRule, CanvasFontKerning, CanvasFontStretch, CanvasFontVariantCaps, CanvasLineCap, CanvasLineJoin, CanvasTextAlign, CanvasTextBaseline, CanvasTextRendering, ClientTypes, CodecState, ColorGamut, ColorSpaceConversion, CompressionFormat, DocumentVisibilityState, EncodedVideoChunkType, EndingType, FileSystemHandleKind, FontDisplay, FontFaceLoadStatus, FontFaceSetLoadStatus, GlobalCompositeOperation, HardwareAcceleration, HdrMetadataType, IDBCursorDirection, IDBRequestReadyState, IDBTransactionDurability, IDBTransactionMode, ImageOrientation, ImageSmoothingQuality, KeyFormat, KeyType, KeyUsage, LatencyMode, LockMode, MediaDecodingType, MediaEncodingType, NotificationDirection, NotificationPermission, OffscreenRenderingContextId, PermissionName, PermissionState, PredefinedColorSpace, PremultiplyAlpha, PushEncryptionKeyName, RTCEncodedVideoFrameType, ReadableStreamReaderMode, ReadableStreamType, ReferrerPolicy, RequestCache, RequestCredentials, RequestDestination, RequestMode, RequestPriority, RequestRedirect, ResizeQuality, ResponseType, SecurityPolicyViolationEventDisposition, ServiceWorkerState, ServiceWorkerUpdateViaCache, TransferFunction, VideoColorPrimaries, VideoEncoderBitrateMode, VideoMatrixCoefficients, VideoPixelFormat, VideoTransferCharacteristics, WebGLPowerPreference, WebTransportCongestionControl, WebTransportErrorSource, WorkerType, WriteCommandType, XMLHttpRequestResponseType

23 interface AddEventListenerOptions extends EventListenerOptions {
   ~~~~~~~~~

  node_modules/typescript/lib/lib.webworker.d.ts:23:1
    23 interface AddEventListenerOptions extends EventListenerOptions {
       ~~~~~~~~~
    Conflicts are in this file.

node_modules/typescript/lib/lib.dom.d.ts:3632:5 - error TS2374: Duplicate index signature for type 'number'.

3632     [index: number]: CSSNumericValue;
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/typescript/lib/lib.dom.d.ts:5234:5 - error TS2374: Duplicate index signature for type 'number'.

5234     [index: number]: CSSTransformComponent;
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/typescript/lib/lib.dom.d.ts:5290:5 - error TS2374: Duplicate index signature for type 'number'.

5290     [index: number]: CSSUnparsedSegment;
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/typescript/lib/lib.dom.d.ts:6471:5 - error TS2374: Duplicate index signature for type 'number'.

6471     [index: number]: string;
         ~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/typescript/lib/lib.dom.d.ts:8412:5 - error TS2374: Duplicate index signature for type 'number'.

8412     [index: number]: File;
         ~~~~~~~~~~~~~~~~~~~~~~

node_modules/typescript/lib/lib.webworker.d.ts:23:1 - error TS6200: Definitions of the following identifiers conflict with those in another file: ImportExportKind, TableKind, ExportValue, Exports, ImportValue, Imports, ModuleImports, ValueType, name, AlgorithmIdentifier, AllowSharedBufferSource, BigInteger, BinaryData, BlobPart, BodyInit, BufferSource, CSSKeywordish, CSSNumberish, CSSPerspectiveValue, CSSUnparsedSegment, CanvasImageSource, DOMHighResTimeStamp, EpochTimeStamp, EventListenerOrEventListenerObject, FileSystemWriteChunkType, Float32List, FormDataEntryValue, GLbitfield, GLboolean, GLclampf, GLenum, GLfloat, GLint, GLint64, GLintptr, GLsizei, GLsizeiptr, GLuint, GLuint64, HashAlgorithmIdentifier, HeadersInit, IDBValidKey, ImageBitmapSource, Int32List, MessageEventSource, NamedCurve, OffscreenRenderingContext, OnErrorEventHandler, PerformanceEntryList, ReadableStreamController, ReadableStreamReadResult, ReadableStreamReader, ReportList, RequestInfo, TexImageSource, TimerHandler, Transferable, Uint32List, XMLHttpRequestBodyInit, AlphaOption, AvcBitstreamFormat, BinaryType, CSSMathOperator, CSSNumericBaseType, CanvasDirection, CanvasFillRule, CanvasFontKerning, CanvasFontStretch, CanvasFontVariantCaps, CanvasLineCap, CanvasLineJoin, CanvasTextAlign, CanvasTextBaseline, CanvasTextRendering, ClientTypes, CodecState, ColorGamut, ColorSpaceConversion, CompressionFormat, DocumentVisibilityState, EncodedVideoChunkType, EndingType, FileSystemHandleKind, FontDisplay, FontFaceLoadStatus, FontFaceSetLoadStatus, GlobalCompositeOperation, HardwareAcceleration, HdrMetadataType, IDBCursorDirection, IDBRequestReadyState, IDBTransactionDurability, IDBTransactionMode, ImageOrientation, ImageSmoothingQuality, KeyFormat, KeyType, KeyUsage, LatencyMode, LockMode, MediaDecodingType, MediaEncodingType, NotificationDirection, NotificationPermission, OffscreenRenderingContextId, PermissionName, PermissionState, PredefinedColorSpace, PremultiplyAlpha, PushEncryptionKeyName, RTCEncodedVideoFrameType, ReadableStreamReaderMode, ReadableStreamType, ReferrerPolicy, RequestCache, RequestCredentials, RequestDestination, RequestMode, RequestPriority, RequestRedirect, ResizeQuality, ResponseType, SecurityPolicyViolationEventDisposition, ServiceWorkerState, ServiceWorkerUpdateViaCache, TransferFunction, VideoColorPrimaries, VideoEncoderBitrateMode, VideoMatrixCoefficients, VideoPixelFormat, VideoTransferCharacteristics, WebGLPowerPreference, WebTransportCongestionControl, WebTransportErrorSource, WorkerType, WriteCommandType, XMLHttpRequestResponseType

23 interface AddEventListenerOptions extends EventListenerOptions {
   ~~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:23:1
    23 interface AddEventListenerOptions extends EventListenerOptions {
       ~~~~~~~~~
    Conflicts are in this file.

node_modules/typescript/lib/lib.webworker.d.ts:1234:5 - error TS2374: Duplicate index signature for type 'number'.

1234     [index: number]: CSSNumericValue;
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/typescript/lib/lib.webworker.d.ts:1266:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'CSSNumericValue' must be of type '{ new (): CSSNumericValue; prototype: CSSNumericValue; parse(cssText: string): CSSNumericValue; }', but here has type '{ new (): CSSNumericValue; prototype: CSSNumericValue; }'.

1266 declare var CSSNumericValue: {
                 ~~~~~~~~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:3664:13
    3664 declare var CSSNumericValue: {
                     ~~~~~~~~~~~~~~~
    'CSSNumericValue' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:1355:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'CSSStyleValue' must be of type '{ new (): CSSStyleValue; prototype: CSSStyleValue; parse(property: string, cssText: string): CSSStyleValue; parseAll(property: string, cssText: string): CSSStyleValue[]; }', but here has type '{ new (): CSSStyleValue; prototype: CSSStyleValue; }'.

1355 declare var CSSStyleValue: {
                 ~~~~~~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:5189:13
    5189 declare var CSSStyleValue: {
                     ~~~~~~~~~~~~~
    'CSSStyleValue' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:1383:5 - error TS2374: Duplicate index signature for type 'number'.

1383     [index: number]: CSSTransformComponent;
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/typescript/lib/lib.webworker.d.ts:1424:5 - error TS2374: Duplicate index signature for type 'number'.

1424     [index: number]: CSSUnparsedSegment;
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/typescript/lib/lib.webworker.d.ts:2247:5 - error TS2374: Duplicate index signature for type 'number'.

2247     [index: number]: string;
         ~~~~~~~~~~~~~~~~~~~~~~~~

node_modules/typescript/lib/lib.webworker.d.ts:2763:5 - error TS2374: Duplicate index signature for type 'number'.

2763     [index: number]: File;
         ~~~~~~~~~~~~~~~~~~~~~~

node_modules/typescript/lib/lib.webworker.d.ts:3075:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'FormData' must be of type '{ new (form?: HTMLFormElement | undefined, submitter?: HTMLElement | null | undefined): FormData; prototype: FormData; }', but here has type '{ new (): FormData; prototype: FormData; }'.

3075 declare var FormData: {
                 ~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:8758:13
    8758 declare var FormData: {
                     ~~~~~~~~
    'FormData' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:4185:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'Notification' must be of type '{ new (title: string, options?: NotificationOptions | undefined): Notification; prototype: Notification; readonly permission: NotificationPermission; requestPermission(deprecatedCallback?: NotificationPermissionCallback | undefined): Promise<...>; }', but here has type '{ new (title: string, options?: NotificationOptions | undefined): Notification; prototype: Notification; readonly permission: NotificationPermission; }'.

4185 declare var Notification: {
                 ~~~~~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:16699:13
    16699 declare var Notification: {
                      ~~~~~~~~~~~~
    'Notification' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:5693:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'URL' must be of type '{ new (url: string | URL, base?: string | URL | undefined): URL; prototype: URL; canParse(url: string | URL, base?: string | undefined): boolean; createObjectURL(obj: Blob | MediaSource): string; revokeObjectURL(url: string): void; }', but here has type '{ new (url: string | URL, base?: string | URL | undefined): URL; prototype: URL; canParse(url: string | URL, base?: string | undefined): boolean; createObjectURL(obj: Blob): string; revokeObjectURL(url: string): void; }'.

5693 declare var URL: {
                 ~~~

  node_modules/typescript/lib/lib.dom.d.ts:22904:13
    22904 declare var URL: {
                      ~~~
    'URL' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:9187:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'onmessage' must be of type '((this: Window, ev: MessageEvent<any>) => any) | null', but here has type '((this: DedicatedWorkerGlobalScope, ev: MessageEvent<any>) => any) | null'.

9187 declare var onmessage: ((this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any) | null;
                 ~~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:28270:13
    28270 declare var onmessage: ((this: Window, ev: MessageEvent) => any) | null;
                      ~~~~~~~~~
    'onmessage' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:9189:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'onmessageerror' must be of type '((this: Window, ev: MessageEvent<any>) => any) | null', but here has type '((this: DedicatedWorkerGlobalScope, ev: MessageEvent<any>) => any) | null'.

9189 declare var onmessageerror: ((this: DedicatedWorkerGlobalScope, ev: MessageEvent) => any) | null;
                 ~~~~~~~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:28272:13
    28272 declare var onmessageerror: ((this: Window, ev: MessageEvent) => any) | null;
                      ~~~~~~~~~~~~~~
    'onmessageerror' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:9216:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'location' must be of type 'Location', but here has type 'WorkerLocation'.

9216 declare var location: WorkerLocation;
                 ~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:27594:13
    27594 declare var location: Location;
                      ~~~~~~~~
    'location' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:9222:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'navigator' must be of type 'Navigator', but here has type 'WorkerNavigator'.

9222 declare var navigator: WorkerNavigator;
                 ~~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:27611:13
    27611 declare var navigator: Navigator;
                      ~~~~~~~~~
    'navigator' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:9224:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'onerror' must be of type 'OnErrorEventHandler', but here has type '((this: DedicatedWorkerGlobalScope, ev: ErrorEvent) => any) | null'.

9224 declare var onerror: ((this: DedicatedWorkerGlobalScope, ev: ErrorEvent) => any) | null;
                 ~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:27967:13
    27967 declare var onerror: OnErrorEventHandler;
                      ~~~~~~~
    'onerror' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:9226:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'onlanguagechange' must be of type '((this: Window, ev: Event) => any) | null', but here has type '((this: DedicatedWorkerGlobalScope, ev: Event) => any) | null'.

9226 declare var onlanguagechange: ((this: DedicatedWorkerGlobalScope, ev: Event) => any) | null;
                 ~~~~~~~~~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:28268:13
    28268 declare var onlanguagechange: ((this: Window, ev: Event) => any) | null;
                      ~~~~~~~~~~~~~~~~
    'onlanguagechange' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:9228:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'onoffline' must be of type '((this: Window, ev: Event) => any) | null', but here has type '((this: DedicatedWorkerGlobalScope, ev: Event) => any) | null'.

9228 declare var onoffline: ((this: DedicatedWorkerGlobalScope, ev: Event) => any) | null;
                 ~~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:28274:13
    28274 declare var onoffline: ((this: Window, ev: Event) => any) | null;
                      ~~~~~~~~~
    'onoffline' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:9230:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'ononline' must be of type '((this: Window, ev: Event) => any) | null', but here has type '((this: DedicatedWorkerGlobalScope, ev: Event) => any) | null'.

9230 declare var ononline: ((this: DedicatedWorkerGlobalScope, ev: Event) => any) | null;
                 ~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:28276:13
    28276 declare var ononline: ((this: Window, ev: Event) => any) | null;
                      ~~~~~~~~
    'ononline' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:9231:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'onrejectionhandled' must be of type '((this: Window, ev: PromiseRejectionEvent) => any) | null', but here has type '((this: DedicatedWorkerGlobalScope, ev: PromiseRejectionEvent) => any) | null'.

9231 declare var onrejectionhandled: ((this: DedicatedWorkerGlobalScope, ev: PromiseRejectionEvent) => any) | null;
                 ~~~~~~~~~~~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:28284:13
    28284 declare var onrejectionhandled: ((this: Window, ev: PromiseRejectionEvent) => any) | null;
                      ~~~~~~~~~~~~~~~~~~
    'onrejectionhandled' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:9232:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'onunhandledrejection' must be of type '((this: Window, ev: PromiseRejectionEvent) => any) | null', but here has type '((this: DedicatedWorkerGlobalScope, ev: PromiseRejectionEvent) => any) | null'.

9232 declare var onunhandledrejection: ((this: DedicatedWorkerGlobalScope, ev: PromiseRejectionEvent) => any) | null;
                 ~~~~~~~~~~~~~~~~~~~~

  node_modules/typescript/lib/lib.dom.d.ts:28288:13
    28288 declare var onunhandledrejection: ((this: Window, ev: PromiseRejectionEvent) => any) | null;
                      ~~~~~~~~~~~~~~~~~~~~
    'onunhandledrejection' was also declared here.

node_modules/typescript/lib/lib.webworker.d.ts:9238:13 - error TS2403: Subsequent variable declarations must have the same type.  Variable 'self' must be of type 'Window & typeof globalThis', but here has type 'WorkerGlobalScope & typeof globalThis'.

9238 declare var self: WorkerGlobalScope & typeof globalThis;
                 ~~~~

  node_modules/typescript/lib/lib.dom.d.ts:27695:13
    27695 declare var self: Window & typeof globalThis;
                      ~~~~
    'self' was also declared here.


Found 28 errors in 2 files.

Errors  Files
     6  node_modules/typescript/lib/lib.dom.d.ts:23
    22  node_modules/typescript/lib/lib.webworker.d.ts:23

Any ideas?

Don`t see the next section of page after the fixed slider in NextJs

I have a NextJs component Slider
which is responsible for the fact that when scrolling, the lower section “runs over” the upper section and overlaps it. Here is code:

"use client"

import { useEffect, useState } from 'react';
import UploadSlider from "./UploadSlider";
import RecommendedCandiates from './RecommendedCandiates';
import WorkWithAI from './WorkWithAI';
import UseSupport from './UseSupport';
import FreeVacancy from './FreeVacancy';

const sections = [
    <UploadSlider key="upload-slider" />,
    <RecommendedCandiates key="recommended-candidates" />,
    <WorkWithAI key="work-with-ai" />,
    <UseSupport key="use-support" />,
    <FreeVacancy key="free-vacancy" />
  ];
  
  const Slider = () => {
  const [currentSection, setCurrentSection] = useState(0);
  const [hasStartedSliding, setHasStartedSliding] = useState(false);

  const startedSlidingHandler = (scrollPosition, triggerHeight) => {
    const sectionHeight = window.innerHeight;
    const newSection = Math.min(
    sections.length - 1,
      Math.floor((scrollPosition - triggerHeight / 2.3) / sectionHeight)
    );
    if (newSection !== currentSection) {
      setCurrentSection(newSection);
    }
  }
  
  const handleScroll = () => {
    const scrollPosition = window.scrollY;
    const triggerHeight = document.getElementById('sliding-sections').offsetTop;

    if (scrollPosition >= triggerHeight && !hasStartedSliding) {
      setHasStartedSliding(true);
    }

    if (hasStartedSliding) {
      startedSlidingHandler(scrollPosition, triggerHeight);
    }
  };

  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, [currentSection, hasStartedSliding]);

  return (
    <>
      <div id="sliding-sections" className="relative">
        <div  style={{height: `${sections.length * 100}vh `}}>
          <div className="min-h-screen">
            {sections[0]}
          </div>
        </div>

        {sections.slice(1).map((section, index) => (
          <div
            key={index + 1}
            className={`fixed top-0 w-full h-full transition-transform duration-1000 ease-in-out transform ${
              hasStartedSliding && currentSection >= index + 1 ? 'translate-y-0' : 'translate-y-full'
            }`}
          >
            {section}
          </div>
        ))}
      </div>
    </>
  );
};

export default Slider;

But the problem I have is that when I place another section under this component on the same page, it is not visible because the slider covers its content.
As far as I understand, this is due to the fact that I define fixed top-0 for the sections in the slider.

Here is page.js code

import EmployerHeader from "@/components/employer/EmployerHeader";
import MainSection from "@/components/employer/MainSection";
import ResumeBase from "@/components/employer/ResumeBase";
import Slider from "@/components/employer/sliders/Slider";
import Reviews from "@/components/employer/Reviews";

export default function Home() {
    return(
        <div className="w-full">
            <EmployerHeader />
            <MainSection />
            <ResumeBase />
            <Slider />
            <Reviews />   
        </div>
    )
}

In my case the Reviews section hides under the Slider component

If I change fixed to absolute, scrolling stops working for me. How can I fix this?

file opener 2 is not working with api level 34 (Android 14)

I am trying to open a pdf file just after downloading it via cordova file transfer plugin. Even after downloading it and passing the exact same path in fileOpener2.open function, i am getting file not found. It does not matter where the file is being stored i just want the file to be displayed just after the download button click.

i tried using every cordova.file.* to set a path for download and use the same path to open but i am getting the same error since. If fileopener2 is not convenient i am okay to use another plugin just to open a downloaded pdf file. I know about the scoped storage stuff in new androids and fileopener2 is not maintained now but i want something to work as the task is extremely simple but due to lack of knowledge in android dev, i am unable to achieve this for the past 2 weeks. I want for both android and ios.

Below is my current code

function downloadFile() {
// Remote URL of the PDF file
var fileUrl =
“”;

      // Local filesystem URL where the file will be saved
      var targetPath =
        cordova.file.externalApplicationStorageDirectory +
        "CRS_Form" +
        ".pdf"; // You can change the target path as needed

      // Check if the FileTransfer plugin is available
      if (typeof FileTransfer !== "undefined") {
        // Initialize the File Transfer Plugin
        var fileTransfer = new FileTransfer();

        // Define the options for the download
        var options = {
          trustAllHosts: true, // Set this to true if you're using a self-signed SSL certificate
        };

        // Start the download
        fileTransfer.download(
          fileUrl,
          targetPath,
          function (entry) {
            // Success callback
            console.log("Download success! File saved to: " + entry.toURL());
            // You can perform additional actions here after successful download
            cordova.plugins.fileOpener2.open(targetPath, "application/pdf", {
              error: function (e) {
                console.log(
                  "Error status: " +
                    e.status +
                    " - Error message: " +
                    e.message
                );
              },
              success: function () {
                console.log("file opened successfully");
              },
            });
          },
          function (error) {
            // Error callback
            console.error("Download error: " + JSON.stringify(error));
          },
          options
        );
      } else {
        // Handle the case when the FileTransfer plugin is not available
        console.error("FileTransfer plugin not available.");
      }
    }

getting error: file not found in the line

cordova.plugins.fileOpener2.open(targetPath, “application/pdf”, {
error: function (e)