Retrieving Data from a Table

I have a table with ID ‘myTable’ and an input Box ID ‘Search’. Normally I type some text into input Text box and retrieve relevant data from the table. The code is working fine, the moment i type any value in input text box, the code responds and gives the desired result without even hitting the Enter Key. But when I select any desired value from the TD (which is normally a word from a sentence), copy the same value and paste it into text box, the code does not respond until and unless the input box is: autofocused by clicking into it; and then entering the Enter/Return Key. Apart from typing of desired value from a sentence of td (as i am presently doing), I wish to paste it into input box with a mouse Click, get the input box populated/autofocused and Enter Key entered into it simultaneously/automatically instead of doing it manually. Will appreciated it the desired code is amended accordingly. thanks n sorry if not being so clear.

<!DOCTYPE HTML>
<HTML>
<HEAD>
<Meta charset="utf-8">
<Meta name="viewport" content="width=device-width, initial-scale=1">


</HEAD>

<TITLE>Equipments Details</TITLE>
<style types="text/css">
body {
  padding: 20px;
}

input {
  margin-bottom: 5px;
  padding: 2px 3px;
  width: 209px;
}

td {
  padding: 4px;
  border: 1px #CCC solid;
  width: 100px;
}
    


</style>


<BODY style="margin-top: 0px; margin-left: 20px; margin-right: 10px;">


<input type="text" id="search" placeholder="Type to search">




<table id="table">
  <tr>
    <td>Chairs and  Pedals</td>
    <td>ہمارے پاس</td>
<td>افلا</td>
  </tr>
  <tr>
    <td>Tools plus Kits</td>
    <td>آج کے دن</td>
<td>یجعلون</td>
  </tr>
  <tr>
    <td>Tractors with Carts</td>
    <td>ٹریکٹرز بمعہ سامان</td>
<td>اَلْھ</td>
  </tr>
</table>




const trs = document.getElementById("myTable").getElementsByTagName("tr");

document.getElementById("search").onkeyup = e => {
    for (const tr of trs)
       tr.style.display = tr.innerText.toLowerCase().includes(e.target.value.toLowerCase()) ? "" : "none";
}

If I type manually the word like Chairs or Tools in text box, the code works. Instead of typing manually, I wish to click any word from a TD of table , the input box may be populated and code executed accordingly. thanks

How would I go about creating a “recently opened” feature like VSCode.dev? [duplicate]

If you where to be on chromium and look at VSCode.dev you can see that is stores what files you have opened with it “recently”. Even if you close the tab and come back to the site a couple days later. I’ve been searching online for how one would go about it but I cant find any info, and when I search the VS code repository I’m only getting IEnumerables (I’m not much of a typescript person) that have similar names to the feature, but nothing about how the feature is done.

How to preserve selection state? [closed]

There is a table and in the table there is checkbox. If I select any row and perform search, this search is being through api call so when new data come already selected row selection got removed. I want to preserve selection on search as well.

I’m using selection model for selection

The easiest way to get the local ISO date

What is the easiest, most clear way to get the current date in the ISO format?

2024-12-31

My current solution is

new Date().toISOString().split('T')[0]);

but it feels dirty and … dated.

I’ve also tried

new Date().format("YYYY-MM-DD");

but it simply gives an error.

Unexpected behaviour in slider’s elements with different heights

I have three sections of weather: current weather, 1-day forecast, and finally, 5-day forecast, all sharing the same class weather section but supposed to have different heights.

I added a slide animation effect to the sections that trigger when the user clicks the corresponding tab.

However, the next slide goes under or on top of the previous one while animating. It takes its normal position only after the animation finishes, as in this example, the ond-day forecast goes under the current weather section and takes its normal position only after the animation ends:

enter image description here

let selectedWeatherSection = 1;
let isFetching = false;

const currentWeatherLabel = document.querySelector('label[for="current-weather"]');

const oneDayForecastLabel = document.querySelector('label[for="one-day-forecast"]');

const fiveDayForecastLabel = document.querySelector('label[for="five-days-forecast"]');

function afterNextRepaint(callback) {
    if (typeof callback !== 'function')
        return;

    requestAnimationFrame(() => {
        requestAnimationFrame(() => {
            callback();
        });
    });
}

function showWeatherSection(n) {
    if (isFetching || selectedWeatherSection === n) // Stop the animation
        return;

    const weatherSections = document.querySelectorAll("main div.container section.weather-section");
    const tabs = document.querySelectorAll("main div.container div.weather-tab div.wrapper label");
    const tempIndex = selectedWeatherSection;

    tabs[selectedWeatherSection - 1].classList.remove("active");

    if (n > weatherSections.length)
        selectedWeatherSection = 1;
    else if (n < 1)
        selectedWeatherSection = weatherSections.length;
    else
        selectedWeatherSection = n;

    isFetching = true;

    const activeWeatherSection = document.querySelector("main div.container section.weather-section.active");
    const nextSection = weatherSections[selectedWeatherSection - 1];
    const nextTab = tabs[selectedWeatherSection - 1];

    if (n > tempIndex) {
        nextSection.classList.add("next");

        afterNextRepaint(() => {
            activeWeatherSection.classList.add("left");
            nextSection.classList.add("left");
        });

        nextSection.addEventListener('transitionend', () => {
                nextSection.classList.add("active");

                activeWeatherSection.classList.remove("left");
                activeWeatherSection.classList.remove("active");

                nextSection.classList.remove("next");
                nextSection.classList.remove("left");

                isFetching = false;
            },
            {once: true}
        );
    } else {
        nextSection.classList.add("prev");

        afterNextRepaint(() => {
            activeWeatherSection.classList.add("right");
            nextSection.classList.add("right");
        });

        nextSection.addEventListener('transitionend', () => {
                nextSection.classList.add("active");

                activeWeatherSection.classList.remove("right");
                activeWeatherSection.classList.remove("active");

                nextSection.classList.remove("prev");
                nextSection.classList.remove("right");

                isFetching = false;
            },
            {once: true}
        );
    }
    nextTab.classList.add("active");
}

const downloadForecast = (forecastDuration, forecastLink) => {
    if (isFetching)
        return

    if (forecastDuration === "one-day")
        showWeatherSection(2);
    else if (forecastDuration === "five-days")
        showWeatherSection(3)

  // some AJAX resuests..
}

currentWeatherLabel.addEventListener('click', () =>
    showWeatherSection(1)
);

oneDayForecastLabel.addEventListener('click', () =>
    downloadForecast("one-day", "./weather/one-day-forecast")
);

fiveDayForecastLabel.addEventListener('click', () =>
    downloadForecast("five-days", "./weather/five-days-forecast")
);
main {
    display: flex;
    justify-content: center;
    padding-top: 50px;
    background: #DCDCDD;
}

main div.container {
    max-width: 1266px;
    width: 60%;
    height: 100%;
    background: #DCDCDD;
}

main div.container > section.weather-section {
    position: relative;
    display: none;
    -webkit-transition: 1s ease-in-out left;
    transition: 1.5s ease-in-out left;
}

main div.container > section.weather-section.next,
main div.container > section.weather-section.prev {
    position: relative;
    top: 0;
    width: 100%
}

main div.container > section.weather-section.next {
    left: 100%
}

main div.container > section.weather-section.prev {
    left: -100%
}

main div.container > section.weather-section.next.left,
main div.container > section.weather-section.prev.right {
    left: 0
}

main div.container > section.weather-section.active.left {
    left: -100%
}

main div.container > section.weather-section.active.right {
    left: 100%
}

main div.container > section.weather-section.active {
    left: 0;
}

main div.container > section.weather-section.active,
main div.container > section.weather-section.next,
main div.container > section.weather-section.prev {
    display: block;
}

.today-weather {
    display: flex;
    flex-wrap: wrap;
    flex-direction: row;
    justify-content: center;
    margin: 23px 0;
}

.today-weather h2 {
    display: block;
    width: 100%;
    text-align: center;
    font-size: 30px;
}

.today-current-weather {
    display: flex;
    width: 65%;
}

.today-current-weather div {
    width: 50%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.current-condition div {
    height: 114px;
    width: 70%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-family: Arial, sans-serif;
    font-size: 16px;
    font-weight: bold;
}

.current-condition-icon img {
    height: 132px;
    width: 144px;
}

.current-highlight {
    display: flex;
    flex-wrap: wrap;
    flex-direction: row;
    margin-bottom: 100px;
}

.current-highlight h2 {
    display: block;
    width: 100%;
    text-align: center;
    font-size: 30px;
}

div.weather-info {
    display: flex;
    width: 100%;
    justify-content: space-around;
    flex-wrap: wrap;
}

.weather-card {
    position: relative;
    background: #f7f7ff;
    width: 30%;
    height: 222px;
    margin: 19px;
    border-radius: 35px;
    display: flex;
    flex-direction: row; /* make child items grow/shrink vertically */
    flex-wrap: wrap;
    align-content: center;
    animation-name: card-animation;
    animation-duration: 1s;
    animation-fill-mode: forwards;
    opacity: 0.2;
}

.weather-card span.weather-card-title {
    position: absolute;
    margin-top: 10px;
    color: #60656F;
    width: 100%;
    height: 20%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: larger;
    text-align: center;
    font-weight: bold;
}

.weather-card div.weather-card-information {
    flex-grow: 1;
    margin-top: 14%;
    height: calc(100% - 20%);
}

div.humidity, div.wind, div.real-temperature-data, div.visibility, div.real-temperature-shade {
    display: flex;
}

.wind-data {
    width: 100%;
}

.wind-data > div {
    height: 50%;
    width: calc(100% - 35px);
}

.humidity-data, .wind-data {
    display: flex;
    flex-direction: column;
}

.humidity-data, .humidity-indicator {
    width: 50%;
}

.humidity-data-percentage, .humidity-data-description {
    height: 50%;
}

.wind-speed, .wind-direction {
    height: 50%;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    padding-left: 35px;
}

.visibility, .visibility-data {
    height: 100%;
}

.visibility-data-percentage, .visibility-data-description {
    height: 50%;
    display: flex;
}

.weather-card div.weather-card-information.uv-index {
    display: flex;
    justify-content: center;
    align-items: center;
}


@keyframes card-animation {
    from {
        transform: translateY(50px);
        opacity: 0.2;
    }
    to {
        transform: translateY(0);
        opacity: 1;
    }
}

.weather-tab {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.wrapper {
    height: 100%;
    width: 55vw;
    background: #fff;
    line-height: 60px;
    border-radius: 40px;
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.25);
}

.wrapper nav {
    position: relative;
    display: flex;
}

.wrapper nav label {
    flex: 1;
    width: 100%;
    z-index: 1;
    cursor: pointer;
    text-align: center;
}

.wrapper nav label a {
    position: relative;
    z-index: -1;
    color: #1d1f20;
    font-size: 20px;
    font-weight: 500;
    text-decoration: none;
    transition: color 0.6s ease;
}

.wrapper nav #home:checked ~ label.current-weather a,
.wrapper nav #inbox:checked ~ label.one-day-forecast a,
.wrapper nav #contact:checked ~ label.five-days-forecast a {
    color: #fff;
}

.wrapper nav label a i {
    font-size: 25px;
    margin: 0 7px;
}

.wrapper nav .tab {
    position: absolute;
    height: 100%;
    width: 33.33%;
    left: 0;
    bottom: 0;
    z-index: 0;
    border-radius: 50px;
    background: linear-gradient(45deg, #05abe0 0%, #8200f4 100%);
    transition: 0.6s cubic-bezier(0.68, -0.55, 0.265, 1.55);
}

.wrapper nav label[for="current-weather"].active ~ .tab {
    left: 0;
}

.wrapper nav label[for="one-day-forecast"].active ~ .tab {
    left: 33.33%;
}

.wrapper nav label[for="five-days-forecast"].active ~ .tab {
    left: 66.66%;
}

.wrapper nav input {
    display: none;
}
<main>
    <div class="container">
        <div class="weather-tab">
            <div class="wrapper">
                <nav>
                    <input type="radio" name="tab" id="current-weather" checked>
                    <input type="radio" name="tab" id="one-day-forecast">
                    <input type="radio" name="tab" id="five-days-forecast">

                    <label for="current-weather" class="weather-tab active">
                        <a href="#">Current weather</a>
                    </label>

                    <label for="one-day-forecast" class="weather-tab">
                        <a href="#">One day forecast</a>
                    </label>

                    <label for="five-days-forecast" class="weather-tab">
                        <a href="#">Five days forecast</a>
                    </label>

                    <div class="tab"></div>
                </nav>
            </div>
        </div>

        <section id="current-weather" class="weather-section active">
            <section class="today-weather">
                <h2>Current Condition</h2>

                <div class="today-current-weather">
                    <div class="current-condition">
                        <div class="weather-card">
                            <div class="current-condition-icon"><img alt="weather-icon" src=""></div>
                        </div>

                        <div class="weather-card">
                            <div class="current-condition-temperature">20</div>
                        </div>
                    </div>

                    <div class="current-condition">
                        <div class="weather-card">
                            <div class="current-condition-time">2024/12/05</div>
                        </div>

                        <div class="weather-card">
                            <div class="current-condition-temperature">Good</div>
                        </div>
                    </div>
                </div>
            </section>

            <section class="current-highlight">
                <h2>Current highlight</h2>

                <div class="weather-info">
                    <div class="weather-card">
                        <span class="weather-card-title">UV index</span>

                        <div class="weather-card-information uv-index">
                            <uv-index value={{uvIndex}}></uv-index>
                        </div>
                    </div>

                    <div class="weather-card">
                        <span class="weather-card-title">Wind status</span>

                        <div class="weather-card-information">
                            <div class="wind">
                                <div class="wind-data">
                                    <div class="wind-speed">
                                        <img src="./images/icons/wind-icon.gif" style="height: 15px;width: 15px" alt="">
                                        150 Km/h
                                    </div>
                                    <div class="wind-direction">30° w</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="weather-card">
                        <span class="weather-card-title">Feels like</span>

                        <div class="weather-card-information">
                            <div class="real-temperature-data">
                                <div class="weather-card-information">25</div>
                            </div>
                        </div>
                    </div>

                    <div class="weather-card">
                        <span class="weather-card-title">Humidity</span>

                        <div class="weather-card-information">
                            <div class="humidity">
                                <div class="humidity-data">
                                    <div class="humidity-data-percentage">60</div>
                                    <div class="humidity-data-description">OK</div>
                                </div>

                                <div class="humidity-indicator">
                                    <humidity-percentage value={{humidity}}></humidity-percentage>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="weather-card">
                        <span class="weather-card-title">Visibility</span>

                        <div class="weather-card-information">
                            <div class="visibility">
                                <div class="visibility-data">
                                    <div class="visibility-data-percentage">55 Km</div>
                                    <div class="visibility-data-description">55</div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="weather-card">
                        <span class="weather-card-title">Temperature in shade</span>

                        <div class="weather-card-information">
                            <div class="real-temperature-shade">
                                <div class="real-temperature-shade-data">
                                    <div class="weather-card-information">30</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </section>

        <section id="one-day-forecast" class="weather-section">
            <h1>One day forecast</h1>
        </section>

        <section id="five-days-forecast" class="weather-section">
            <h1>Five days forecast</h1>
        </section>
    </div>
</main>

I would like to know why this is happening and how I can fix it

How do I let GPT use a large JS library (like Express) to generate code?

I want GPT (e.g., GPT-4) to generate code snippets based on a large JavaScript library like Express.js. Because the library’s source is too big to paste directly into the prompt, how can I give GPT enough context so it produces accurate, library-specific code?

I’ve heard about using embeddings or vector databases to store the code and then retrieving only the relevant parts. Is there a simple method or tool that can help me give GPT what it needs to generate code built on top of Express, without exceeding token limits or losing important details?

Reference: https://github.com/expressjs/express

How can I use Android Java Interfaces in a frida JavaScript code?

I’ve been grinding my teeth over implementing Android Stackwalker with frida. Getting a StackWalker instance is easy and I can call any basic method pretty easily, BUT, when it comes to the Java forEach method I need to pass a function implementing the Java Consumer Interface but I don’t really know how to generate one because writing one in javascript will not be accepted by the java method.

var StackWalker = Java.use('java.lang.StackWalker');
var walker = StackWalker.getInstance();
var Consumer = Java.use('java.util.function.Consumer');
function cons(frame) {
    send({ id: "Ok", message : "blablabla" })
};               // <- How to implement Consumer interface ?
walker.forEach(cons);

Thanks in advance for any help !

I tried changing the implementation of the forEach method but then I can’t get the inherent variables aka the stackframes

How to avoid CORs issues when accessing R2?

I’m getting the following CORs error when using the exif-js library:

Failed to load resource: Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. Status code: 200

What’s confusing is, the images are loading fine when using the img tag. Additionally, I have set the R2 CORs policies as follows:

[
  {
    "AllowedOrigins": [
      "http://localhost:3000",
      "http://127.0.0.1:3000",
      "*"
    ],
    "AllowedMethods": [
      "GET",
      "HEAD",
      "POST",
      "PUT",
      "DELETE"
    ],
    "AllowedHeaders": [
      "Authorization",
      "Content-Type",
      "Origin",
      "Accept",
      "X-Requested-With",
      "Access-Control-Request-Method",
      "Access-Control-Request-Headers"
    ],
    "ExposeHeaders": [
      "ETag",
      "Cache-Control",
      "Content-Length",
      "Content-Range",
      "Content-Type",
      "Date",
      "Last-Modified"
    ]
  }
]

which should allow for access from anywhere. What am I doing wrong?

Here is a minimal reproducible example. The img loads fine, but I get a CORs error when using the exif library:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>EXIF Data Viewer</title>
    <script src="https://cdn.jsdelivr.net/npm/exif-js"></script>
</head>
<body>
    <img src="https://someurl.com/img.jpeg" id="img" style="max-width: 500px;">

    <script>
        console.log('setting hook')
        window.onload = function() {
            const img = document.getElementById('img');
            EXIF.getData(img, function() {
                const exifData = EXIF.getAllTags(this);
                console.log('EXIF Data:', exifData);
            });
        };
    </script>
</body>
</html>

Java script : I cant seem to display canvas element in my html

HTML

 <div id="enemy-area" class="enemy-area">
            <canvas id="enemy-canvas"></canvas>
            <div id="ea-1" class="ea"></div>
            <div id="ea-2" class="ea"></div>

CSS

#enemy-area{
            display: grid;
            position: relative;
            grid-template-columns: repeat(3, 1fr);
            grid-auto-rows: minmax(20vh, 1fr);
            gap: 5px; 
            text-align: center;
            width: 35vh;
            height: 60vh;
            overflow: hidden;
            margin: auto;
            
        }

 #enemy-canvas{
            position: absolute;
            top: 70%; /* Center vertically */
            left: 50%; /* Center horizontally */
            transform: translate(-50%, -50%);
            width: 50%; /* Adjust based on desired size */
            height: 50%; /* Adjust based on desired size */
            z-index: 20;
            pointer-events: none;
        }  

Java script

import Character from './Character.js';

export default class Enemy extends Character {
    constructor(name, maxHP, HP, defense, imageSrc, healthBarId, team, type, statusHP, ATK, temporaryATK, temporaryDEF) {
        super(name, maxHP, HP, defense, imageSrc, healthBarId, team, type, statusHP, ATK, temporaryATK, temporaryDEF);

        this.name = name || 'Enemy';
        this.maxHP = maxHP || 12;
        this.HP = HP || 12;
        this.defense = defense || 0;
        this.imageSrc = imageSrc || '../texture/CHARACTER/enemy1.png';
        this.healthBarId = healthBarId || 'enemy-health-bar';
        this.team = team || 'enemy-area';
        this.type = type || 'enemy-object';
        this.statusHP = statusHP || 'enemy-hp';
        this.ATK = ATK || 0;
        this.temporaryATK = temporaryATK || 0;
        this.temporaryDEF = temporaryDEF || 0;

        // Animation properties
        this.spriteWidth = 64;
        this.spriteHeight = 64;
        this.staggerFrames = 8;
        this.gameFrame = 0;
        this.scale = 2.9;
        this.spriteAnimationsEnemy = {};
        this.animationStates.forEach((state, index) => {
            let frames = { loc: [] };
            for (let j = 0; j < state.frames; j++) {
                let positionX = j * this.spriteWidth;
                let positionY = index * this.spriteHeight;
                frames.loc.push({ x: positionX, y: positionY });
            }
            this.spriteAnimationsEnemy[state.name] = frames;
        });

        this.currentAnimation = 'wave,right'; // Default animation

        // Load the sprite sheet
        this.spriteSheet = new Image();
        this.spriteSheet.src = this.imageSrc;
        this.spriteSheet.onload = () => {
            console.log(`Enemy sprite sheet loaded successfully: ${this.spriteSheet.src}`);
        };
        this.spriteSheet.onerror = () => {
            console.error(`Failed to load sprite sheet: ${this.spriteSheet.src}`);
        };

        // Initialize canvas after DOM is ready
        document.addEventListener('DOMContentLoaded', () => this.initializeCanvas());
    }

    // Initialize the canvas and its context
    initializeCanvas() {
        this.enemyElement = document.getElementById('enemy-canvas');
        if (!this.enemyElement) {
            console.error("Canvas element for enemy not found. Ensure the HTML contains a canvas with ID 'enemy-canvas'.");
            return;
        }

        console.log(`Canvas element found: ${this.enemyElement.id}`);
        const devicePixelRatio = window.devicePixelRatio || 1;
        this.enemyElement.width = this.enemyElement.clientWidth * devicePixelRatio;
        this.enemyElement.height = this.enemyElement.clientHeight * devicePixelRatio;
        this.context = this.enemyElement.getContext('2d');
        if (!this.context) {
            console.error("Failed to initialize 2D context for enemy canvas.");
            return;
        }

        this.context.scale(devicePixelRatio, devicePixelRatio);
        this.context.imageSmoothingEnabled = false;

        console.log("Canvas and context initialized successfully.");
    }

    // Animate the enemy
    animateEnemy() {
        if (!this.enemyElement || !this.context || !this.spriteSheet.complete) {
            console.error("Animation prerequisites not met. Ensure canvas, context, and sprite sheet are properly initialized.");
            return;
        }

        this.gameFrame++;

        // Get the current animation and frame position
        const animation = this.spriteAnimationsEnemy[this.currentAnimation];
        if (!animation) {
            console.error(`Animation state '${this.currentAnimation}' not found.`);
            return;
        }

        const position = Math.floor(this.gameFrame / this.staggerFrames) % animation.loc.length;
        const frame = animation.loc[position];

        // Clear the canvas
        this.context.clearRect(0, 0, this.enemyElement.width, this.enemyElement.height);

        // Calculate scaled dimensions
        const scaledWidth = Math.round(this.spriteWidth * this.scale);
        const scaledHeight = Math.round(this.spriteHeight * this.scale);

        // Center the image
        const destX = (this.enemyElement.width - scaledWidth) / 2;
        const destY = (this.enemyElement.height - scaledHeight) / 2;

        // Draw the current frame
        this.context.drawImage(
            this.spriteSheet,
            frame.x, frame.y,       // Source frame (x, y)
            this.spriteWidth,       // Source frame width
            this.spriteHeight,      // Source frame height
            destX, destY,           // Destination (x, y)
            scaledWidth,            // Scaled width
            scaledHeight            // Scaled height
        );
    }

// Initialize the enemy and start animation
const enemy = new Enemy(
    'Enemy',
    80,
    80,
    0,
    '../texture/CHARACTER/enemy1.png',
    'enemy-health-bar',
    'enemy-object',
    'enemy-hp',
    5,
    0,
    0
);

// Main animation loop
function animate() {
    enemy.animateEnemy(); // Update the enemy's animation
    requestAnimationFrame(animate); // Request the next frame
}

// Start the animation loop
animate();

these are the code for my game project, and it does not display the canvas on the screen, even if I inspect the webpage it is still not there. I really don’t know whats the problem, Im a total noob in JS, ple someone help

I tried changing or resizing the CSS, and also the JS especially below where you create and initialize the character, it actually works for the other character but it does not work for the enemy character. I tried copying the other character but the canvas is still not showing up

CORS Issue with Google Apps Script and Chrome Extension: “Response to preflight request doesn’t pass access control check”

I’m developing a Chrome extension that sends a POST request to a Google Apps Script web app. However, I’m encountering the following CORS error in the browser:

Access to fetch at ‘https://script.google.com/macros/s/deployId/exec’ from origin ‘https://www.youtube.com’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

Here’s the relevant part of my Chrome extension code:

function postSheet() {
  console.log("a");
  chrome.storage.sync.get(["apiKey"], function (result) {
    const apiKey = result.apiKey || "";
    const googleData = {
      type: "messageUsage",
      apiKey: apiKey,
    };
    const url = "https://script.google.com/macros/s/deployId/exec";

    fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      redirect: "follow",
      body: JSON.stringify(googleData),
    })
      .then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`);
        }
        return response.json();
      })
      .then(data => {
        console.log("Google Sheet response:", data);
      })
      .catch(error => {
        console.error("Error posting to Google Sheet:", error);
      });
  });
}

Here’s the server-side code running on Google Apps Script:

function doPost(e) {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  try {
    if (JSON.parse(e.postData.contents).apiKey) {
      var apiKey = JSON.parse(e.postData.contents).apiKey;
      var customer = findRowByUniqueId(sheet, apiKey);

      return ContentService.createTextOutput(sheet.getRange(customer, 9).getValue())
        .setMimeType(ContentService.MimeType.JSON);
    }

    return ContentService.createTextOutput(JSON.stringify("success"))
      .setMimeType(ContentService.MimeType.JSON)
      .addMetaTag("Access-Control-Allow-Origin", "*");

  } catch (error) {
    return ContentService.createTextOutput(JSON.stringify({
      status: 'error',
      message: error.toString()
    })).setMimeType(ContentService.MimeType.JSON);
  }
}

What I’ve Tried

Setting CORS Headers:

I tried adding .addMetaTag(“Access-Control-Allow-Origin”, “*”) and setting the MIME type to JSON in the Apps Script response. It didn’t work.

Using no-cors Mode:

Switching the fetch mode to no-cors avoids the error but doesn’t allow me to process the JSON response.

Chrome Extension Permissions:

I’ve verified that my manifest.json has the necessary permissions, including <all_urls> and storage.

Avoiding Preflight Requests:

I attempted to simplify headers to avoid OPTIONS preflight requests but didn’t succeed.

Proxy

I also tried cors-anywhere

What I Expect

How can I correctly set the Access-Control-Allow-Origin header in Google Apps Script to resolve this issue?
Is there a recommended approach for enabling JSON-based communication between a Chrome extension and Google Apps Script?
I want to send each message to a Google Apps Script with the person’s API key and get the total number of messages from there.

Any guidance would be greatly appreciated. Thanks in advance!

Bootstrap Selectpicker Not Displaying old() Value in Laravel Form

I am using Laravel’s Form::select along with Bootstrap’s selectpicker in my form. My dropdown is supposed to display the old value (retrieved using old() function) after form validation fails. However, the selected value is not showing correctly when selectpicker is applied.

Here’s my current code:

{!! Form::select(
    'edit_promotionId',
    $promotions,
    old('edit_promotionId'),
    [
        'class' => 'form-control selectpicker',
        'data-live-search' => 'true',
        'id' => 'edit_promotionId'
    ]
) !!}

Without selectpicker, the old value is displayed as expected. However, when I add selectpicker, the selected value is not shown.

What I tried:

  • Ensured that old('edit_promotionId') returns the correct value.
  • Inspected the generated HTML, and the selected attribute is set correctly on the corresponding <option> tag.
  • Called $('.selectpicker').selectpicker('refresh') in my JavaScript, but it still doesn’t work.

Question:

  • How can I ensure the old() value is displayed correctly in the dropdown when using Bootstrap selectpicker? Am I missing any additional steps to synchronize selectpicker with the old() value?

Close Popover in vue when clicked on Link

I Tried using a pretty nasty solution by using bools and v-if:

const popoverOpen = ref(false)

function closePopover() {
  console.log("Popover wird geschlossen")
  popoverOpen.value = false
}
function openPopover() {
  popoverOpen.value = true
}

Template

        <Popover class="relative">
          <PopoverButton 
          class="flex items-center gap-x-1 text-sm/6 font-semibold text-[#E0D8DE] hover:text-[#949D6A]"
          @click="openPopover"
          >
            Dashboard
            <ChevronDownIcon class="size-5 flex-none text-gray-400" aria-hidden="true" />
          </PopoverButton> 

<PopoverPanel
          v-if="popoverOpen" 
          class="absolute -left-8 top-full z-10 mt-3 w-screen max-w-md overflow-hidden rounded-3xl bg-[#1a1a1a] shadow-lg ring-1 ring-gray-900/5"
          >
            <div class="p-4">
              <div v-for="item in products" :key="item.name" class="group relative flex items-center gap-x-6 rounded-lg p-4 text-sm/6 hover:bg-[#423E37]">
                <div class="flex size-11 flex-none items-center justify-center rounded-lg bg-gray-50 group-hover:bg-white">
                  <component :is="item.icon" class="size-6 text-gray-600 group-hover:text-indigo-600" aria-hidden="true" />
                </div>
                <div class="flex-auto">
                  <router-link 
                    v-if="item.href" 
                    :to="item.href" 
                    class="block font-semibold text-[#949D6A]"                       
                    @click="closePopover"          
                    >
                    {{ item.name }}
                  </router-link>
                  <p class="mt-1 text-[#E0D8DE]">{{ item.description }}</p>
                </div>
               </div>
              </div>

thats a pretty nasty solution and
to open the Dropdown again, you’ll have to click twice (because it first have to update ref)

Question: Has anyone a good and clean solution for this problem.

I am using “use strict” in this function still auto global is happening in my code. can someone helpesme [closed]

I am using “using strict” still auto-global happening why? can some help me ?

"use strict"

function fun() { //  fun --> global scope

  var x = 10; //  x --> fun scope

  function gun() { // gun --> fun scope
    var y = 10; // y --> gun scope
    console.log(x); //10
    console.log(y); //10
  }

  gun();
}

fun();

I am using “use strict” console.log(x) is not a part of gun – scope so here its happening auto – global and executing it which should not as I am using “use strict”
functionality.

Why does this JavaScript code cause a memory leak despite cleaning up all references?

I have a question about a memory leak I’m able to create in Google Chrome. By creating a Div element, adding it to the DOM, and removing it later the element is never removed from memory.

const addDiv = () => {
    const div = document.createElement('div');
    div.innerHTML = 'test';
    document.body.appendChild(div);
    // - Wait to cleanup the DIV
    setTimeout(() => div.remove(), 200);
};

setTimeout(() => addDiv(), 5000);

I’ve uploaded an image of chrome dev tools showing the DIV in memory.
Single DIV in memory

Below is another image running this function on an interval to show how this can add up.

setInterval(() => addDiv(), 100);

Set interval memory

What is strange is that you can fix the memory leak by slowing down the setInterval to a time greater than the promise.

setInterval(() => addDiv(), 300);

Working Memory

Is this a chrome bug, or is this desired Javascript behavior? I don’t understand why running the code once on a timeout would keep the Div in memory, but running it forever on an interval frees it.