Why use try except for fetch api when we can directly return the values?

Ive seen many eexamples in the internet where the fetch api calls are like

async function getData() {
  const url = "https://example.org/products.json";
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(Response status: ${response.status});
    }
    return json
    const json = await response.json();

  } catch (error) {
    return error;
  }
}

but why are we throwing errors just to return it? cant we directly return error when !reponse.ok.

here is wht i mean

async function getData() {
  const url = "https://example.org/products.json";
  
    const response = await fetch(url);
    if (!response.ok) {
      return new Error(Response status: ${response.status});
    }

    const json = await response.json();
    return json
}


How Can I Make Vimeo’s Javascript Player API iframe body Fill instead of Contain?

I want to embed an iframe that contains a vimeo video inside a container div and give that div any ole aspect-ratio and just have my vimeo video conform to that using something like object-fit: cover (even though that isn’t available for <iframe> elements).

Is there some sort of magical Vimeo JS API embed setting that will make the video “cover” the entire browser viewport rather than be “contained” in it?

Here’s an example URL: https://player.vimeo.com/video/764297424?h=04309e89de&badge=0&autoplay=1&muted=1&controls=0&loop=1&autopause=0&title=0&byline=0&playsinline=1&background=1&responsive=1&pip=0&dnt=1&chromecast=0

Notice how when you resize the browser to various aspect ratios, the video is contained rather than filling/covering the viewport.

How to open component’s dialog from another component in react?

I have a main component, App(). I have another component, Event(). Event has a dialog, defined in a separate file, that opens and populates from a click on a table row. In that case, the data in the dialog can be modified and saved to a database.

Now the second case is to create a new event. The Add button for that is in another component. When clicked, I want Event to open its dialog, un-populated.

I’ve seen many similar examples but I can’t get them to work for my use case. I think I need to useContext but I don’t get how to apply it. Here’s some code to clarify:

index.tsx

ReactDOM.createRoot(document.getElementById("root")!).render(
  <App/>
);

App.tsx

const App = () => {    
  return (
    <Router>
          <MainAppBar isAppSidebarOpen={false} />
    </Router>
  );
};

The router goes to Event page from menu click in MainAppBar. A click on a table row opens and populates a MUI dialog. It will open just by setting the open property to true.

event.tsx

  function handleRowClick(event: React.MouseEvent<unknown>, id: number) {
    const selectedRowData = getSelectedRowData(id);
    setDialogData(selectedRowData);
    setOpen(true);
  }

Now I need to open the same dialog, unpopulated, on a button click in the App component.

function ClickAddIconComponent(props: { key: string }) {
    return (
      <Fab size="small" color="primary" aria-label="add" onClick={handleAddIconClick} sx={{ marginTop: "6px", textAlign: "right"}}>
        <AddIcon />
      </Fab>
    )
  }
}

function handleAddIconClick() {
  <TellEventPageToOpenDialog message="openEmptyDialog" />;
}  

I’m assuming I need to useContext() to open Event’s dialog?

interface MessageContextType {
  message: string;
  setMessage: React.Dispatch<React.SetStateAction<string>>;
}

const MessageContext = React.createContext<MessageContextType | null>(null);

const TellEventPageToOpenDialog = (props:any) => {
  const [message, setMessage] = React.useState(props.message);

  return (
    <MessageContext.Provider value={{ message, setMessage }}>
      <EventPage />
    </MessageContext.Provider>
  );
}

Now how do I get Event receive the message and open its dialog? Am I going about this wrong?

Is it possible to retrieve an entire directory from a web URL at once?

I’m currently attempting to scrape a wiki for some image files. I have determined that every image I want is hosted at a URL with the following structure:

https://static.wikia.nocookie.net/<game name>/images/X/XY/<file name.png>

In all cases I know the exact file name corresponding to the image I’m searching for. However, here’s my issue: X is always a one-digit hexadecimal number e.g. 3, and XY is always a two-digit hexadecimal number whose first digit is the same as X, e.g. 3c. But as far as I can tell these numbers are completely arbitrary and there is no way to reliably predict them in advance for a specific image I want to retrieve.

My plan moving forward is to search through the entire web directory until I find the files I want, check the exact URL they are stored at, and write them to a local file for instantaneous subsequent lookup. To accomplish this, I see two options:

  1. For a given X and XY, I could somehow retrieve the entire directory at .../images/X/XY/, check what files are stored there, and write all of the URLs to a local file.
  2. For a given file name, I iterate through all possible combinations of X and XY until I find where the file is stored, and write its URL to a local file.

In total I have several thousand images I want to find the URLs for. Given that, option 1 would appear to be an astronomically faster approach, but I’m not sure if retrieving an entire directory of files from the web at once is possible. Can it be done with HTTPS requests (I’m using Node.js for reference)? If not, are there any other tools I could potentially use, or will I have to resort to option 2?

Console Error: Uncaught ReferenceError: functioName is not defined – Javascript

I have a js file that loads onto my page, that contains this code:

    function m_ASSUREV17() {
    document.getElementById("t_ASSUREV17").innerHTML = t_ASSUREV17;
    document.getElementById("c_ASSUREV17").innerHTML = c_ASSUREV17; 
    document.getElementById('p_ASSUREV17').src=p_ASSUREV17;
    document.getElementById('u_ASSUREV17').href=u_ASSUREV17+var_TRACK;
    }
         
    console.log("ASSUREV17");

When I call function m_ASSUREV17() on the page:

    <script>
    m_ASSUREV17();
    </script> 

I get this error:

Uncaught ReferenceError

m_ASSUREV17 looks clearly defined to me, and the console log confirms that the file loaded, what could possibly be the issue here?

If the console loads the log message, doesn’t that mean the function declared before it, indeed defines m_ASSUREV17?

Thanks!

jsPDF html method – autoPaging option with the ‘text’ mode causes issues with text styling

Good day, I wanted to ask a question related to using the html method of jsPDF to generate a PDF based on the html contents of a page. I am using Vue 3 for my frontend and Laravel 10 for my backend. The issue lies specifically with using the autoPaging option. It works well for text alone, however, if the text has any styling attached to it, such as a background color or borders, when the page breaks, the text gets correctly pushed downward onto the next page, but the background color and border get cut off and the styling gets misaligned. I am attaching my code to show a simple generation of this error with a repeated h1 element that crosses the boundary from one page to another.

*Also to add some more context, html2canvas-pro was used instead of html2canvas, because an oklch error was occurring with some of the color functions in the codebase when using the original version of html2canvas, and this error was resolved when using the updated one. It was also necessary since jsPDF uses html2canvas under the hood. Lastly, the px-scaling was a hotfix that was added to jsPDF’s list of hotfixes, and it creates more accurate pixel scaling when rendering, so that is why that option was chosen.

Code:

<script setup>

import { Head } from '@inertiajs/vue3';
import { jsPDF } from "jspdf";
import { onMounted, ref } from 'vue';
import html2canvas from "html2canvas-pro"; 

window.html2canvas = html2canvas;

function capture(){
    const doc = new jsPDF({
        orientation: 'p',
        unit: 'px',
        format: 'a4',
        hotfixes: ['px_scaling'],
        });


    doc.html(document.getElementById('pdf-container'), {
        callback: function (doc) {
            doc.save();
    },
        margin: [60, 20, 60, 20],
        autoPaging: 'text',
        width: 754,
        windowWidth: 900,
    });

}


</script>

<template>
    
<div id="pdf-container" class="pdf-container">

    <h1 v-for="x in 50">This is a test h1 element.</h1>
    
<button class="btn mt-8 btn-neutral" @click="capture()">Download PDF</button>

</div> <!--end of pdf container-->


</template>

<style scoped>

.pdf-container{
    @apply w-full p-12 pt-4 bg-white;
    font-family:'Arial', sans-serif;
    letter-spacing: 0.01px;
    
}


h1{
    @apply font-bold text-2xl border border-black;
}


</style>

This image below shows what is generated when that Download PDF button is clicked.

Styling for the border at the edge of the page gets misaligned while the text is preserved.

Another example where instead of border, a background color is applied, but it similarly loses its style formatting.

Why I can access httpOnly Cookies using Nuxt useCookie() composable?

In my Nuxt app, I’ve implemented custom authentication middleware and composables. On the backend (Spring Boot), my /login route sets a refreshToken as an HttpOnly cookie and returns an accessToken in the response body.

From my research, I understand that HttpOnly cookies should not be accessible via JavaScript on the client side. However, in my Nuxt custom composable useAuth(), I’m able to access the refreshToken using the useCookie(‘refreshToken’) composable — even though the cookie was set with the HttpOnly flag.

This behaviour confuses me. I was under the impression that such cookies are strictly inaccessible from JavaScript. Is Nuxt doing something under the hood that exposes these cookies? Or could this be a misconfiguration on my part?

Clarifications:

  1. I’m certain that my cookie is httpOnly from browser devtools

Compare objects by contents in Javascript [duplicate]

When you compare objects with JavaScript’s == operator, it compares by identity: it will produce true only if both objects are precisely the same value.

Comparing different objects will return false, even if they have identical properties.

let object1 = {value: 10};
let object2 = {value: 10};

console.log(object1 == object2);
// → false

How to deepCompare objects by contents (identical properties and corresponding value). I have tried:

function deepCompare(a, b) {
  if (a === b) return true;

  if (typeof a !== "object" || typeof b !== "object" || a == null || b == null) {
    return false;
  }

  let keysA = Object.keys(a);
  let keysB = Object.keys(b);

  if (keysA.length !== keysB.length) return false;

  for (let key of keysA) {
    if (!keysB.includes(key) || !deepCompare(a[key], b[key])) {
      return false;
    }
  }

  return true;
}

let a = { name: "Alice", age: 30 };
let b = { name: "Alice", age: 30 };

console.log(a === b);         // false
console.log(deepCompare(a, b)); // true

But it seems to be slow. Is there any optimal way to do this.

Why does sqrt(x+1)-sqrt(x) result to 0 in JS? [duplicate]

I’m trying to compute the difference between two square roots in JS.

function diffSqrt(x) {
  return Math.sqrt(x + 1) - Math.sqrt(x);
}

console.log(deltaSqrt(1e6));   // 0.0004999998750463419
console.log(deltaSqrt(1e12));  // 5.00003807246685e-07
console.log(deltaSqrt(1e16));  // 0.0

Why does it go all the way to 0.0 for a larger x?

I just wrote the straightforward implementation subtracting two square roots. I expected something small but non-zero like 5e-11.

Chrome extension needing to be clicked several times to remove CSS

I have a Chrome extension which adds a CSS to a website, and I want to have that CSS be able to be removed when the extension icon is clicked.

I was able to get the CSS to inject successfully but I was not able to properly find a way to remove the CSS. When I click the extension icon, it doesn’t remove the CSS. Instead, you need to click it serveral times for the CSS to be removed.

Here is the code I’m using as background.js. It inserts CSS into the tab and then should remove the CSS when the action/extension is clicked:

chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
  if (tab.url?.startsWith('https://example.com')) {
    await chrome.scripting.insertCSS({
      files: ['style.css'],
      target: { tabId: tabId }
    });
    await chrome.action.enable(tabId);
  }
});

chrome.action.onClicked.addListener(async (tab) => {
  if (tab.url?.startsWith('https://example.com')) {
    await chrome.scripting.removeCSS({
      files: ['style.css'],
      target: { tabId: tab.id }
    });
  }
});

manifest.json:

{
  "manifest_version": 3,
  "name": "__MSG_application_title__",
  "description": "__MSG_application_description__",
  "version": "1.0.0",
  "default_locale": "en_US",
  "icons": {
    "16": "images/icon-16.png",
    "32": "images/icon-32.png",
    "48": "images/icon-48.png",
    "128": "images/icon-128.png"
  },
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_title": "Toggle dark mode"
  },
  "host_permissions": [
    "*://example.com/*"
  ],
  "permissions": [
    "scripting"
  ]
}

I tried calling chrome.scripting.removeCSS multiple times which does solve the problem but for obvious code quality problems this solution isn’t satisfactory:

chrome.action.onClicked.addListener(async (tab) => {
  if (tab.url?.startsWith('https://example.com')) {
    await chrome.scripting.removeCSS({
      files: ['style.css'],
      target: { tabId: tab.id }
    });
    await chrome.scripting.removeCSS({
      files: ['style.css'],
      target: { tabId: tab.id }
    });
    await chrome.scripting.removeCSS({
      files: ['style.css'],
      target: { tabId: tab.id }
    });
    await chrome.scripting.removeCSS({
      files: ['style.css'],
      target: { tabId: tab.id }
    });
    await chrome.scripting.removeCSS({
      files: ['style.css'],
      target: { tabId: tab.id }
    });
    await chrome.scripting.removeCSS({
      files: ['style.css'],
      target: { tabId: tab.id }
    });
    await chrome.scripting.removeCSS({
      files: ['style.css'],
      target: { tabId: tab.id }
    });
  }
});

Does anyone know why this behavior happens and how to properly solve it?

JavaScript string includes with UTF-16 characters

I have a search string and a source string. I want to test if the search string is included in the source string.

Search Source
C Сon
str.codePointAt(0) 67 1057

You can see that the source string’s first character looks like a capital letter “C”, but is UTF-16 number 1057 making it not the same as typing “C” on your keyboard which is UTF-16 number 67.

These two encodings of a capital letter “C” are close enough that they should match, but how do I perform the test?

source.includes(search) returns false because the source doesn’t contain “C” (#67).

I have heard this is called a homoglyph. How do I perform the test without needing a big map of character equivalents? Is there a built-in JS function?

Swiper.js Marquee/Ticker effect is not moving

I’m trying to build a Swiper Marquee/Ticker for a logo garden, but the I’m experiencing some issues, I cannot get the Swiper to actually start moving on its with AutoPlay. When I interact with the Swiper it will start playing automatically, but until then it just stays frozen.

import Swiper from 'swiper'
import { Autoplay } from 'swiper/modules'
import 'swiper/css'

const Ticker = () => {
    const swiper = new Swiper('.image-ticker', {
        modules: [Autoplay],
        slidesPerView: 'auto',
        spaceBetween: 120,
        loop: true,
        speed: 4000,
        autoplay: {
            delay: 1,
            disableOnInteraction: false,
        },
    })
}

export default Ticker

<div class="swiper image-ticker">
<div class="swiper-wrapper">
<div class="swiper-slide"><img src="someimage.jpg"></div>
<div class="swiper-slide"><img src="someimage.jpg"></div>
<div class="swiper-slide"><img src="someimage.jpg"></div>
<div class="swiper-slide"><img src="someimage.jpg"></div>
<div class="swiper-slide"><img src="someimage.jpg"></div>
<div class="swiper-slide"><img src="someimage.jpg"></div>
<div class="swiper-slide"><img src="someimage.jpg"></div>
<div class="swiper-slide"><img src="someimage.jpg"></div>
</div>
</div>

How do i add :hover and :active events to my tampermonkey injected script?

I’m injecting a script using tampermonkey (and html with css in the javascript) and i want to add :hover and :active events to my injected buttons to make them prettier
how do i do this?

        for (let region of data) {
            for (let lobby of region.lobbies) {
                let button = document.createElement('button');
                
                button.textContent = `${region.region} ${lobby.gamemode} ${lobby.numPlayers}p`;
                button.addEventListener('click', () => {
                    // TODO: add team integer
                    window.open(`https://diep.io/?ip=${lobby.ip}&g=${lobby.gamemode}&l=0x0`)
                });
                button.style.padding = "5px";
                button.style.border = "1px solid black";
                button.style.backgroundColor = colors[region.region] || "rgba(255, 255, 255, 0.5)";

                buttons.appendChild(button);
            }
            let br = document.createElement('br');
            buttons.appendChild(br);

this is where i update my buttons every second
i have tried asking people and googling but i havent found an answer

of course i cannot really add that css in without using javascript to do so

Vite: [plugin:vite:import-analysis] Failed to resolve import “../assets/sample” from “src/components/Navbar/Navbar.jsx”

Vite: [plugin:vite:import-analysis] Failed to resolve import “../assets/sample” from “src/components/Navbar/Navbar.jsx”
”’
import { assets } from “../assets/sample”;
”’
However, when I run the development server, I receive the following error:

[plugin:vite:import-analysis] Failed to resolve import “../assets/sample” from “src/components/Navbar/Navbar.jsx”. Does the file exist?

The file structure is as follows:
src/
├── assets/
│ ├── sample.js
│ └── logo.png
├── components/
│ └── Navbar/
│ └── Navbar.jsx

In sample.js, I’m importing images and exporting them as an object:
”’
import logo from ‘./logo.png’;

export const assets = {
logo,
// other assets…
};
”’

My questions:

Why is Vite unable to resolve the import from sample.js?

Why does the assets object have the type any in my IDE?

How can I correctly import and use images in this setup?

Despite the file existing and the paths seeming correct, Vite throws the import analysis error.
Additionally, when I hover over assets in my IDE, it shows the type as any.

I’ve tried restarting the development server and checking the file paths, but the issue persists.

types.d.ts is not being automatically included in every TypeScript file

I’ve noticed that the types.d.ts file in the root of the project was automatically included in every TypeScript file in my project. I didn’t have to write import type {...} from "./types.d.ts"; in every file manually, which is a very convenient feature.

But recently, that stopped being the case. VSCode shows errors when not writing the line above. What did I do? Could it be something with my tsconfig.json? More importantly, how do I get it back?

{
    "compilerOptions": {
        "target": "ESNext",
        "module": "ESNext",
        "moduleResolution": "Node",
        "strict": true,
        "esModuleInterop": true,
        "skipLibCheck": true,
        "forceConsistentCasingInFileNames": true,
        "paths": {
            "*": [
                "./node_modules/*"
            ]
        },
        "types": ["./types.d.ts"],
        "rewriteRelativeImportExtensions": true
    }
}

I manually included .ts extensions in import modules because at first I used tsc, which outputted the built files in the same place as the normal files, but that’s beyond the scope of my question.
Also, I have not tried compiling without the ./types.d.ts import. The problem I have as of now is with VSCode.

Extra context: I can’t provide types.d.ts because of privacy reasons, but I do have one import in it:

import { CacheType, ChatInputCommandInteraction } from "discord.js/typings";