How Can I Resolve a CORS Error When Loading Scripts Hosted on AWS S3 and Served by CloudFront?

I encountered a CORS error when trying to load a script <script src="https://d**.cloudfront.../chunk-... /> (the host is another domain), as indicated in the network tab:

enter image description here

The scripts are hosted on AWS S3 and delivered through CloudFront. Despite configuring the CORS policy in CloudFront, the error persists.

Additionally, I executed curl -I and received the following response:

HTTP/2 200
content-type: application/javascript
content-length: 121954
date: Tue, 12 Dec 2023 06:47:12 GMT
last-modified: Mon, 11 Dec 2023 17:33:28 GMT
etag: "f0edb133eff23e82ce02******b584"
server: AmazonS3
vary: Accept-Encoding
x-cache: Miss from cloudfront
via: 1.1 b12493f4f82b360a236f8747***********a.cloudfront.net (CloudFront)
x-amz-cf-pop: TLV50-C2
x-amz-cf-id: u4Egm965M6u_IEOv******Xw_YLGvJkZsges_FBoTtBQ==
vary: Origin

What further steps can I take to resolve this CORS issue?

enter image description here

Unable to integrate keycloak with angular Js 1.x — seeking Guidence

I am reaching out to seek your guidance on integrating Keycloak authentication into an Angualar JS 1.x application.

We have an existing application registered on Keycloak, and we have the necessary credentails, including the realm, URL, and client ID. Now we are looking to enhance the security of our application by incorporating token-based authentication with Keycloak.

If there are any best practives, recommended resources, tutorials, or code samples that you could share to guide us through this process, it would be immensely helpful for our development

I appreciate your time and expertise in advance and thank you for contributing to the strength of the Keycloak community. We look forward to benefiting from your insights.

Thanks

Access local storage in Chrome Extension

I want to access local storage in chrome extension based on manifest version 3

I am having a local-storage item with key as name now i want to console the name every time it changes in local storage in chrome extension

earlier it was used to be like this

chrome.storage.onChanged.addListener(function (changes, namespace) {
chrome.action.setBadgeText({text:changes.total.newValue.toString();
chrome.action.setBadgeBackgroundColor({color: '#9688F1'});
});

But not working with version 3

what can be done to do this

PWA won’t go fullscreen after deinstall/install

My PWA worked happily in manifest -> display: fullscreen for years. Yesterday I came across a recent Chrome/Android bug where my PWA would no longer auto rotate from lansdscape/portrait. Having seen in SO that the fix required a de-install and re-install of my PWA I went ahead.

Good news, is my PWA is once again responsive to orientation change.

Bad news, my PWA with not go back to fullscreen mode and maxes out at standalone 🙁

I have upped the version on my cache to hopefully reload all files but still no joy.

Please help!

Yes, you have to grant geolocation access but all the code is available on github.

To reproduce: –

Please navigate to this URL and

  • If you don’t have a Google Maps API key just click “No Maps!”
  • Wait a bit and you will be prompted to install the PWA.
  • Click install
  • Exit Android Chrome
  • Go to your phone “Apps” scroll across and you should see Brotkrumen with a ginger-bread house icon.
  • The app launches in standalone mode and not fullscreen.
  • Watch the wicked witch capture Hansel and Gretel

ScreenShot example of PWA trip replay

How to properly import external javascript file?

In accordance with Home Assistant documentation, I should import external javascript files like below –

import "https://api-maps.yandex.ru/2.1/?apikey=1&module";

but when I do so I get the following error –

?lang=ru_RU&amp;apikey=1&module:1 Uncaught TypeError: Cannot read properties of undefined (reading 'performance')
at ymapsInit (?lang=ru_RU&amp;apikey=1&module:1:84)
at ?lang=ru_RU&amp;apikey=1&module:1:28837

the error leads to the following code –

(function ymapsInit(e) {
    var n = this
      , t = {
        ns: {},
        supports: {},
        env: e
    };
    t.performance = {
        now: n.performance && n.performance.now ? n.performance.now.bind(n.performance) : function() {
            return Date.now()
        }
    },

Since this is external code, I can not modify it.
Here is the working example of the same code, but not within Home Assistant.

How could I fix it?

Phone Number input field accept only number in javascript

<form id="enquiryForm" name="wf-form-Enquiry-Form-2" data-name="Enquiry Form" >
    <input type="text" class="form-input-field w-input" maxlength="256" name="Name" data-name="Name" placeholder="Name*" id="name" required="">
    <input type="email" class="form-input-field w-input" maxlength="256" name="Email" data-name="Email" placeholder="Email*" id="Email" required="">
    <input type="text" class="form-input-field w-input" maxlength="256" name="Company" data-name="Company" placeholder="Company*" id="Company" required="">
    <input type="text" class="form-input-field w-input" maxlength="256" name="Phone" data-name="Phone" placeholder="Phone" id="Phone" required="">
    <textarea id="Project-Detail" name="Project-Detail" maxlength="5000" data-name="Project Detail" placeholder="Tell us about your project" class="form-input-field text-area w-input"></textarea>
    <div class="w-embed">
        <input type="hidden" class="button-position" name="Position" value="">
    </div>
    <input type="submit" value="Book Free Call" data-wait="Please wait..." class="button red-btn form w-button">
</form>

I’ve been working on a nocode design studio landing page, and I’m currently tackling the phone number validation. I want to make sure that only numbers are accepted in the phone number field. Here’s the part of the code I’ve been working on for this. Any tips or suggestions would be appreciated!

Feel free to provide more details or ask for specific assistance if needed!

I need solution by Javascript only.

Merging a new string, containing number characters, with an existing number string

I have this string:

let sx = ";1,2,3,4;5;10,11;"

The string has individual parts, separated by “;” which then are separated by “,” thus the parts are as follows:

1,2,3,4 and 5 and 10,11

Numerically, the parts will always be in ascending order, but not necessarily consecutive.

The website’s user then creates another “part”, which might be “6,7,8,9”, always consecutive, always different than any part of “sx”, but random (it could be “28,29,30” or “15”). I have named this part “s1”. The goal now is to join “sample” with “s1” and sort it, according to the first number of each part. Here is what I have tried:

let sx = ";1,2,3,4;5;10,11;";
let s1 = "6,7,8,9";

//join "sx" with "s1", and split the new string by ";":
s1 = sx.concat(";" + s1 + ";");
s1 = s1.split(";").filter(Boolean);

//sort s1 by the first number of each part:
s1.sort(function(a, b) {
    var ax = a[0], bx = b[0];
    return parseInt(ax) - parseInt(bx);
});

console.log(s1);

Even though I use “parseInt”, the result in the above example returns: “1,2,3,4,10,11,5,6,7,8,9”.

What I need is: “1,2,3,4,5,6,7,8,9,10,11” with the individual parts being:

“1,2,3,4” and “5” and “6,7,8,9” and “10,11”, so then I can update the original string “sx” properly.

What am I doing wrong? By the way, I am not entirely sure if the end result is a string or an array(?), so please excuse the question’s title!

I want to get a formula to calculate pokemon damage

My problem is that I want the result of the total damage to be based on the maximum life of my entity and his level (1-100), I mean that if the damage is 70, and the maximum life of the victim is 70, that a certain percentage be lowered without using floats or percentages.

Those are stats that im trying to use.

damagerDamage = 45
entityLevel = 1
maxEntityHealth = 45

This is the formula that ive been using.
totalResult = maxEntityHealth * damagerDamage / entityLevel

Its should be less, since im using the max Health in the formula, it goes crazy, so yeah i dont know what to do. Can anyone help me?

The problems results:

maxEntity: 45
totalResult: 2025

Generating Consistent Key Pair with crypto.subtle in JavaScript Using Same Input

You’ve mentioned that you’re working on a JavaScript project and want to use crypto.subtle to generate a key pair. However, you’re encountering an issue where, despite using the same password input, the generated private keys are different each time. Your goal is to have a deterministic process so that the same password input always produces the same key pair output.

To address this issue, you’ve tried introducing a fixed salt, but the problem persists. You are seeking guidance on how to achieve a consistent key pair generation based on the same password input using crypto.subtle in JavaScript.
(Enhanced and highly complex password input.)

async function generateKeyPairFromPassword(password) {
  try {
    // PW to ArrayBuffer
    const encoder = new TextEncoder();
    const passwordBuffer = encoder.encode(password);

    //  PBKDF2 
    const key = await crypto.subtle.importKey(
      'raw',
      passwordBuffer,
      { name: 'PBKDF2' },
      false,
      ['deriveKey']
    );

    const derivedKey = await crypto.subtle.deriveKey(
      {
        name: 'PBKDF2',
        salt: new Uint8Array([]),
        iterations: 100000,
        hash: 'SHA-256',
      },
      key,
      { name: 'AES-GCM', length: 256 },
      true,
      ['encrypt', 'decrypt']
    );

    // for seed
    const symmetricKeyBuffer = await crypto.subtle.exportKey('raw', derivedKey);
    const symmetricKey = await window.crypto.subtle.importKey(
      'raw',
      symmetricKeyBuffer,
      { name: 'AES-GCM', length: 256 },
      true,
      ['encrypt', 'decrypt']
    );

    // RSA keypair
    const keyPair = await crypto.subtle.generateKey(
      {
        name: 'RSA-OAEP',
        modulusLength: 2048,
        publicExponent: new Uint8Array([1, 0, 1]),
        hash: 'SHA-256',
      },
      true,
      ['encrypt', 'decrypt']
    );

    // pubkey
    const exportedPublicKey = await crypto.subtle.exportKey('spki', keyPair.publicKey);

    // prikey
    const exportedPrivateKey = await crypto.subtle.exportKey('pkcs8', keyPair.privateKey);

    // tob64
    const publicKeyBase64 = arrayBufferToBase64(exportedPublicKey);
    const privateKeyBase64 = arrayBufferToBase64(exportedPrivateKey);

    console.log('Generated Public Key from Password (Base64):', publicKeyBase64);
    console.log('Generated Private Key from Password (Base64):', privateKeyBase64);

    return keyPair;
  } catch (error) {
    console.error('Error generating key pair from password:', error);
    throw error;
  }
}

// ArrayBuffer 转为 Base64
function arrayBufferToBase64(buffer) {
  const bytes = new Uint8Array(buffer);
  return btoa(String.fromCharCode.apply(null, bytes));
}

// gen
generateKeyPairFromPassword('your-password').then((keyPair) => {
  
});

How do I fix searchbar breaking styles

I was making a way to search through a list of YouTube videos on my site, but I found that whenever I type something in the search bar it breaks the wrapping/styling of the videos.

Before I type

After I type

I don’t really know javascript well at all, so it could be a problem with that.

This is my css/html/js for the videos/search:

div.item {
    vertical-align: top;
    display: inline-block;
    text-align: left;
    width: 270px;
}
img {
    width: 256px;
    height: 144px;
}
.meta {
    display: block;
}
<div class="item" style="display: none;"><img src="https://i.ytimg.com/vi/XXXXX/hqdefault.jpg"><span class="meta">Title</span><div class="meta"><span>ID</span><span>&nbsp;&nbsp;·&nbsp;&nbsp;</span><span>Date</span></div><br><br></div>


function search_videos() { 
    let input = document.getElementById('search-bar').value 
    input=input.toLowerCase(); 
    let x = document.getElementsByClassName('item'); 
      
    for (i = 0; i < x.length; i++) {  
        if (!x[i].innerHTML.toLowerCase().includes(input)) { 
            x[i].style.display="none"; 
        } 
        else { 
            x[i].style.display="list-item";                  
        } 
    } 
}

I want it to show up like the first image when searching and not one video on each line.

Vue component maximum recursive updates exceeded with vite HMR

When I changed something in a Vue nested component and saved it. The Vite HMR will constantly reload the component. And then it caused a warning of vue: Maximum recursive updates exceeded…

Environment: Vue3 + Vite 4.x/5.x

Demo on stackblitz.
Change something in Child1.vue and save. You can see 101 times same info and a warning in console.

Thanks for help.

Only rerender/reload once.

time tracking in google sheet

I am looking to track time in days in this google sheet. Essentially, I’d whenever something is added in column A I’d like the time tracking to begin for that column. When the status is changed I’d like to record the total amount of time in terms of days. Has anyone seena javascript that can do this in google sheet?

enter image description here

I found this javascript from another problem but I dont know how to edit it to get what i need.

Vue Pinia doesn’t update reactive state more than once

In my vue application, the structure is like this:
App.vue
-GroupWrapper
–GroupListing
-PeopleWrapper
–PeopleListing
-ConversationWrapper

I have a user store that uses pinia, and my main use of it is calling user.findChats() in the App.vue

App.vue

import { useChatStore } from './stores/chat'
import { useUserStore } from './stores/user'

const chat = useChatStore()
const user = useUserStore()

chat.findChats();

where it finds all the chats and if it’s of the type “dm” it adds it to the dm_chats array and if it’s the type “gm” it adds it to the gm_chats array,

chat.js

import { defineStore } from 'pinia'
import { db } from '../firebase'
import { collection, query, where, getDocs } from 'firebase/firestore'
import { useUserStore } from './user'

export const useChatStore = defineStore('chat', {
  state: () => ({
    dm_chats: [],
    gm_chats: [],
    user: useUserStore(),
  }),
  actions: {
    async findChats(id) {
      const chatsRef = collection(db, 'chats')
      const q = query(chatsRef, where('chat_users', 'array-contains', this.user.id))
      await getDocs(q).then((querySnapshot) => {
        querySnapshot.forEach((docu) => {
          if (docu.data().type == 'dm') {
            this.dm_chats.push(docu.id)
          } else {
            this.gm_chats.push(docu.id)
          }
        })
      })
    }
  }
})

Where the dm_chats should be displayed in a v-for in PeopleListing

PeopleWrapper.vue

<script setup>
import peopleListing from './people-listing.vue'
import { useChatStore } from '../../stores/chat'
import { storeToRefs } from 'pinia';

const chat = useChatStore()
const { dm_chats: chats } = storeToRefs(chat)
</script>

<template>
  <div>
    <div>
      Direct Chats
    </div>
    <div>
      <peopleListing v-for="dm_chat in chats" :dm_chat="dm_chat" />
    </div>
  </div>
</template>

and the same for gm_chats in GroupListing,

However after for looping over the array, the only update on screen is once, only when it fetches from firestore the document for a chat of type “gm”, even tho when using Vue Devtools or console.log, the dm_chat and gm_chat are properly populated, it’s just not updating them.

What I’ve tried was:

  • Unified both stores into one file
  • Changing the pinia syntax from option to setup
  • Using reactive in the array when it was setup
  • Using computed instead of storeToRefs both in setup and options syntax, I even tried using both at the same time.
  • Tried the $subscribe method
  • Tried the vue watch method

After all that, it had the same result.
Now this is probably me missing something very basic, but I can’t for the life of me find out what it is. This also isn’t with just the dm_chats or the gm_chats, this is with every other variable in both the user and chat stores. So if anyone could let me know what I’m missing, I’d be super thankful.

Hitting breakpoints with Vite Preview

I’m using Vite to build a React application. Currently, I just have the default counter application when I use the React template with Vite. If I run npm run dev, then launch VS Codes debug mode with chrome, I’m able to put a breakpoint at the [count, setCount] line for the following code:

    import { useState } from 'react'
    import './App.css'
    
    function App() {
      const [count, setCount] = useState(0)
    
      return (
        <>
          <h1>component-a</h1>
        </>
      )
    }
    
    export default App

When I select “Step Over” I can see the “count” variable set to 0 in the variables tab.
However, if I try to use npm run build to create a minified version of this; if I then run npm run preview and attempt to launch VS Codes chrome debug. I no longer have access to the break points. If I try to put a break point in the same place, I get an error that says “unbound break point” when I hover over the spot where the break point should be. I’ve enabled source maps in my vite.config.js file and attempted to set a value for “sourceMapPathOverrides” in launch.json Here are the following files:

vite.config.js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  build: {
    "sourcemap": true
  },
  css: {
    devSourcemap: true,
  },
})

launch.json

{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
    {
  "name": "React App - Package A",
  "type": "chrome",
  "request": "launch",
  "url": "http://localhost:4173", // Update with the appropriate URL
  "webRoot": "${workspaceFolder}/packages/component-a",
  "sourceMapPathOverrides": {
    "webpack:///./src/*": "${webRoot}/src/*"
  }
},
]
}

I do adjust the url value in launch.json from port 5173 to 4173 when switching to npm run preview.

Also, if I hover over the unbound breakpoint error, and select “trouble shoot launch configuration” I’m directed to the following message in debug diagnostics:

✅ This breakpoint was initially set in:

C:Usersuser.namemonorepo-react-vitepackagescomponent-asrcApp.jsx line 5 column 1

❓ We couldn't find a corresponding source location, and didn't find any source with the name App.jsx.

How did you expect this file to be loaded? (If you have a compilation step, you should pick 'sourcemap')
Loaded in directlyBe parsed from a sourcemap
Here's some hints that might help you:
Make sure your build tool is set up to create sourcemaps.

Ultimately, this is supposed to be part of a monorepo and I’d eventually like to build to packages, publish them and be able to use them in other applications with full debug functionality. But for now, I’m having trouble getting full debug functionality when running a single package; particularly with getting break points to work.

I cannot abort requests with axios AbortController

I’ am trying to abort requests but nothing works as if the abort method is ignored.
When I click the button, a repeated request has to be canceled.

`const controllerRef = useRef();

async function handleSubmit(ev: React.FormEvent) {
ev.preventDefault();

if (controllerRef.current) { // check if there is already a request
  console.log("cancel");
  controllerRef.current.abort(); // if there is than abort()
}

controllerRef.current = new AbortController();
const signal = controllerRef.current.signal;

try {
  const response = await axios.post("http://localhost:3000/find", {
    email,
    number,
    signal,
  });

  console.log(response.data);
} catch (error) {
  console.error("Error:", error);
}

}`

I tried to use useRef to keep current state of new AbortController() and it seems it keeps but for some reasons the abort() does not work.