value setter for a custom select element with lazy loading

I am trying to mimic the behavior of the HTMLSelectElement value setter to work at any time, but also retain lazy loading of my custom elements. I use a base class which cache elements of the same type to prevent their template from being loaded multiple times:

const templateCache = new Map();

export class DSElement extends HTMLElement {
  constructor() {
    super();
    this._name = this.constructor._type;
    this.attachShadow({ mode: 'open' });
    this._internals = this.attachInternals();
  }

  async connectedCallback() {
    let template = templateCache.get(this._name);

    if (!template) {
      const templateUrl =
        chrome.runtime.getURL(`interface/templates/${this._name}.html`);
      const response = await fetch(templateUrl);
      const html = await response.text();

      const wrapper = document.createElement('template');
      wrapper.innerHTML = html;

      const inner = wrapper.content.getElementById(`${this._name}-template`);
      if (inner) {
        template = inner;
        templateCache.set(this._name, template);
      }

      requestAnimationFrame(() => this._after());
    }

    if (template)
      this.shadowRoot.appendChild(template.content.cloneNode(true));
  }

  async _after() {
    // Virtual method
  }
}

Then I create a DSSelect class which handles drawing stuff inside the _after method:

import { DSElement } from './ds-element.js';

class DSSelect extends DSElement {
  static _type = 'ds-select';
  
  constructor() {
    super();
    this._value = null;
    this._firstOption = null;
    this._label = null;
    this._internals.role = 'select';
  }

  async _after() {
    this._select = this.shadowRoot.getElementById('select');
    this._options = this.shadowRoot.getElementById('options');
    this._labelSpan = this.shadowRoot.getElementById('label');

    this.setInitialSelection();

    this._select.addEventListener('click', () => this.toggle());
    this.addEventListener('click', e => this.handleOptionClick(e));
  }

  setInitialSelection() {
    let firstOption;
    if (this._firstOption !== null)
      firstOption = this._firstOption;
    else
      firstOption = this.querySelector('ds-opt');
    if (firstOption)
      this.selectOption(firstOption);
  }

  selectOption(option) {
    this._value = option.getAttribute('value');
    this._label = option.textContent;
    this._labelSpan.innerText = this._label;
    this.dispatchEvent(new Event('change', {bubbles: true}));
  }

  get value() {
    return this._value;
  }

  set value(value) {
    const match = Array.from(this.querySelectorAll('ds-opt')).find(
      opt => opt.getAttribute('value') === value
    );

    if (match)
      this._firstOption = match;
  }
}

customElements.define(
  DSSelect._type, DSSelect
);

And somewhere in my code I use the setter on DOMContentLoaded event:

const reloadOptions = () => {
  const elMode = document.getElementById('mode');
  elMode.value = 'selected';
};

document.addEventListener('DOMContentLoaded', reloadOptions);

This actually works 99% of the time, until I hold down F5 to reload quickly many times. I think there is an asynchronous race happening between reloadOptions and _after function and this.querySelectorAll('ds-opt') appears empty inside the DSElement setter when _after loose.

I am not sure though what would be the correct approach here.

For completeness, the template for ds-select looks like this:

<template id="ds-select-template">
  <style>
    :host {
      display: inline-block;
      position: relative;
      user-select: none;
    }
    
    #select {
      cursor: pointer;
    }

    #options {
      display: none;
      position: absolute;
      top: 100%;
      left: 0;
      right: 0;
    }

    #options.open {
      display: block;
    }
  </style>
  <div id="select">
    <span id="label">n/a</span>
  </div>
  <div id="options">
    <slot></slot>
  </div>
</template>

And finally the ds-select element is used like:

<ds-select id="mode">
  <ds-opt value="all">
    Parse all
  </ds-opt>
  <ds-opt value="selected">
    Parse selected
  </ds-opt>
</ds-select>

html attribute does not exist for Python requests-html response object as stated in documentation

I’ve been looking for a library to help render the javascript of webpages and found requests-html. Seems to be what I was looking for, however, upon following the documentation I discovered the response object does not have an html attribute so accessing anything in that path (as follows) will not be recognised

session = HTMLSession()

r = session.get(url)

r.html.links

I am curious if this occurred prior to the lxml_html_clean module was separated from the rest of the project or should it be functioning perfectly fine regardless and my installation of the library is not correct.

How can I reliably click YouTube’s “Skip Ad” button via content script in a Chrome extension?

I’m working on a Chrome extension that automatically clicks the “Skip Ad” button on YouTube videos to save us from watching those pesky ads.

I’ve got a content script that tries to find the skip button using several selectors and then simulates a user click by firing mouse events and calling .click(). It also mutes the video while ads play. The script runs with a MutationObserver on the player and a fallback interval every few seconds.

Here’s a snippet of my main click function:

function tryClickSkip() {
  if (!cachedSkipButton || !document.contains(cachedSkipButton)) {
    cachedSkipButton = findSkipButton();
  }

  if (cachedSkipButton && typeof cachedSkipButton.click === 'function') {
    cachedSkipButton.dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));
    cachedSkipButton.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
    cachedSkipButton.dispatchEvent(new MouseEvent('mouseup', { bubbles: true }));
    cachedSkipButton.click();
    console.log('Clicked skip ad button!');
  }
}

The problem: the console logs confirm the click happened, but the ad doesn’t actually skip. It seems like YouTube might require some kind of user gesture or additional interaction that I’m missing.

Has anyone successfully automated clicking YouTube’s skip ad button? Am I missing a trick to simulate the user click better, or is there a better approach altogether?

Thanks in advance for any tips or pointers!

python -playwright mouse pointer UI enable

I want a playwright python mouse UI enable script.
so can i can see my mouse to be working in visual for my humanize automation.
if any one can provide me any method or js script that will work plz come forward and drop here.

def mouseUI(page: Page) -> None:
    page.add_init_script("""
        (() => {
            const dot = document.createElement('div');
            dot.id = '__mouse_dot__';
            Object.assign(dot.style, {
                position: 'fixed',
                width: '8px',
                height: '8px',
                borderRadius: '50%',
                backgroundColor: 'red',
                zIndex: '2147483647',  // Max z-index
                pointerEvents: 'none',
                top: '0px',
                left: '0px',
                transform: 'translate(-50%, -50%)',
                transition: 'top 0.03s linear, left 0.03s linear'
            });
            document.body.appendChild(dot);

            window.addEventListener('mousemove', e => {
                dot.style.left = `${e.clientX}px`;
                dot.style.top = `${e.clientY}px`;
            });
        })();
    """
)

i tried out this method although it did not worked .
also i am expecting a mouse UI js or something that can enable a pointer in my chromium playwright browser so that i can visually see my mouse pointer pointing and analyize it [speed , clicking, moving , static]

Refresh token being revoked, probebly because login consent

I have the following scenario:

  1. User logs in via google auth with basic scopes

  2. After he logs in he can sync website’s calendar with google calendar, a consent opens and asks permission for calendar scopes.

  3. After permission granted I save the refresh token in the database.

After a few days I noticed that the refresh that I stored is not valid, even that it should be valid intill it revoked.

After some debugging I noticed that the login with google ganarete refresh token even that it’s not suppose to.

here my client initilize for the login:

                const clientGoogle = window.google.accounts.oauth2.initCodeClient({
                    client_id: CLIENT_ID,
                    scope: 'email profile openid',
                    redirect_uri: redirectUri,
                    callback: handleGoogleResponse,
                    ux_mode: 'redirect',
                    select_account: true,
                    include_granted_scopes: true,
                    //access_type: 'offline'//no need offline access, because no need the refresh token
                });

And here google initilization for the calndar part:

                const clientGoogle = window.google.accounts.oauth2.initCodeClient({
                    client_id: CLIENT_ID,
                   scope: 'https://www.googleapis.com/auth/calendar',
                    redirect_uri: redirectUri, // Use dynamic origin instead of hardcoded URL
                    callback: handleGoogleResponse,
                    access_type: 'offline',
                    include_granted_scopes: true, // Enable incremental authorization         
                    select_account: true,
                    login_hint: user?.user?.email,
                    prompt: 'consent',
                    response_type: 'code',
                });

chrome browser beforeunload api unwished action issue

I have a question about the browser beforeunload API.

I wanted to implement a feature that displays a warning window when performing actions such as refreshing, going back, closing a tab, or moving to another URL on a specific page. However, even though I implemented it, it does not work as intended.

When the page with the beforeunload API applied is loaded, the action does not work when using the back button, closing a tab, or moving to another URL in the Chrome browser. However, once the loaded page is clicked, the function works for those actions. Additionally, after the page is loaded, only the F5 (refresh) key works properly with the API, and subsequent actions (back button, close tab button, moving to another URL) also work properly. I am curious about why these issues are occurring. I am uploading the sample code below, which also exhibits the same issues.

Development environment: Chrome browser, VSC, Live Server extension

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
</head>

<body>
    <h4>
        sample
    </h4>
    <form>
        <textarea placeholder=""></textarea>
    </form>

    <script type="text/javascript">
        window.addEventListener('beforeunload', (event) => {
            
            event.preventDefault();

            
            event.returnValue = '';
        });
    </script>
</body>

</html>

I want to enable the beforeunload function when the user clicks the back button, closes the tab, or navigates to another URL on the loaded page.

How to build a call chain in javascript

The task is as follows:
We need to execute tasks in several threads that depend on maxThreads, but tasks with the same IDs cannot be executed simultaneously, otherwise an error will pop up. We need to create such an execution chain, where tasks with different IDs are executed in parallel, and tasks whose ID is already in progress are added to the task queue and executed when the task with the same ID has finished its execution.

This is what I managed to write, several threads are called. But I can’t make it so that when the task with one ID is finished, it would be possible to call the task from the queue.

I can’t make the correct call chain.

Important! All tasks that come to us from the iterator must be completed.

const executeData = {
    running: {},
    completed: {}
}

const tasks = [];
for (const i of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) {
    tasks[i] = [];
    for (const action of ['init', 'prepare', 'work', 'finalize', 'cleanup']) {
        tasks[i].push({
            targetId: i,
            action: action,
            _onExecute() {
                this.running = true;
            },
            _onComplete() {
                delete this.running;
                this.completed = true;
            }
        });
    }
}

const q = [...tasks[0], ...tasks[1]];

tasks[0][4]._onComplete = () => {
    q.push(...tasks[1], ...tasks[2], ...tasks[3]);
    delete tasks[0][4].running;
    tasks[0][4].completed = true;
};
tasks[1][1]._onComplete = () => {
    q.push(...tasks[4]);
    delete tasks[1][1].running;
    tasks[1][1].completed = true;
};
tasks[2][2]._onComplete = () => {
    q.push(...tasks[5]);
    delete tasks[2][2].running;
    tasks[2][2].completed = true;
};
tasks[3][3]._onComplete = () => {
    q.push(...tasks[6]);
    delete tasks[3][3].running;
    tasks[3][3].completed = true;
};
tasks[4][4]._onComplete = () => {
    q.push(...tasks[7]);
    delete tasks[4][4].running;
    tasks[4][4].completed = true;
};
tasks[5][4]._onComplete = () => {
    q.push(...tasks[8]);
    delete tasks[5][4].running;
    tasks[5][4].completed = true;
};
tasks[8][4]._onComplete = () => {
    q.push(...tasks[9], ...tasks[10], ...tasks[11]);
    delete tasks[8][4].running;
    tasks[8][4].completed = true;
};

const queue = {
    [Symbol.asyncIterator]() {
        let i = 0;
        return {
            async next() {
                while (q[i] && (q[i].completed || q[i].acquired)) {
                    i++;
                }
                if (i < q.length) {
                    const value = q[i++];
                    if (value) {
                        value.acquired = true;
                    }
                    return {
                        done: false,
                        value
                    };
                } else {
                    return {
                        done: true,
                        value: undefined
                    };
                }
            }
        };
    },
    q
};



async function run(maxThreads = 0) {

    maxThreads = Math.max(0, maxThreads || 12)
    const activeTargetId = new Set();
    const taskQueue = [];
    let taskInQueue = 0;
    const queueIterator = queue[Symbol.asyncIterator]()

    async function executeNext() {
        const { value: task, done } = await queueIterator.next();

        if (done) return;

        if (activeTargetId.has(task.targetId)) {
            taskQueue.push(task)
            await executeNext()

            return;

        }

        if (taskInQueue < maxThreads) {
            activeTargetId.add(task.targetId);
            taskInQueue++
            await executeTask(task).finally(() => {
                activeTargetId.delete(task.targetId);
                taskInQueue--
            })

        }


        await executeNext();

    }

    async function startTaskQ(targetId) {
        const nextTask = taskQueue.find(task => task.targetId === targetId);

        if (nextTask) {

            try {
                await executeTask(nextTask);
                activeTargetId.add(nextTask.targetId);
            } finally {
                activeTargetId.delete(nextTask.targetId);
                const nextTaskId = taskQueue.findIndex(task => nextTask.targetId === task.targetId);
                taskQueue.splice(nextTaskId, 1);
                startTaskQ(targetId);

            }
        }
    }

    const workres = [];
    for (let i = 0; i < maxThreads; i++) {
        workres.push(executeNext())
    }

    await Promise.all(workres);
    console.log(executeData, 'executeData')
}



async function executeTask(task) {
    const running = executeData.running;
    const completed = executeData.completed;
    const targetId = task.targetId;

    if (running[targetId]) {
        throw new Error(`cannot execute task ${targetId}:` +
            `${task.action}: task with the same targetId=${targetId} is running`);
    }


    running[targetId] = task;
    const ns = { ...running }
    console.log(ns, 'running')
    if (task._onExecute) {
        task._onExecute();
    }



    switch (task.action) {
        case 'init': {
            await sleep(10 * (1 + targetId / 10));

            await sleep(30 * (1 + targetId / 10));
            break;
        }
        case 'prepare': {
            await sleep(30 * (1 + targetId / 10));
            await sleep(70 * (1 + targetId / 10));
            break;
        }
        case 'work': {
            await sleep(50 * (1 + targetId / 10));
            await sleep(150 * (1 + targetId / 10));
            break;
        }
        case 'finalize': {
            await sleep(30 * (1 + targetId / 10));
            await sleep(70 * (1 + targetId / 10));
            break;
        }
        default: {
            await sleep(25);
            await sleep(25);
            break;
        }
    }



    delete running[targetId];

    if (task._onComplete) {
        task._onComplete();
    }



    if (!completed[targetId]) {
        completed[targetId] = [];
    }
    completed[targetId].push({ targetId: task.targetId, action: task.action });

}


async function sleep(ms) {
    ms = Math.max(0, ms);
 
    return new Promise(r => setTimeout(() => r(), ms));
}

run(3)

React Leaflet update external component when click on map

A very cool feature of dashboards is a map (e.g. a choropleth world map) that when you click on it (e.g. you click on a country) other tables and charts in the dashboard are updated to show country specific information. I would like to build this using React, Leaflet and a chart library (e.g. recharts or something) for the external tables/charts.

For an example of what I mean, see this highchart dashboard

On the react-leaflet documentation page I found this, which I think demonstrates that it is possible: https://react-leaflet.js.org/docs/example-external-state/

I could not, however, find any other examples that more closely fit my description (spend quite some time searching on Stack Overflow and Google). This then makes me wonder whether this is actually possible using React leaflet.

Can this be done?

Is there an eslint rule to disallow checking if a Record/object is true?

I want an ESLint rule that disallows the following:

filteredParams: Record<string, string> = {};
if (filteredParams) {
        resource += "?" + new URLSearchParams(filteredParams).toString();
    }

But isn’t going to complain about “Unnecessary conditional, the types have no overlap”, which is what @typescript-eslint/strict-boolean-expressions and @typescript-eslint/no-unnecessary-condition do to my other code.

return value !== null && value !== undefined;

javascript: No Access-Control-Allow-Origin’ header is present on the requested resource

I wrote a simple program that when touch a button on html page he make a XMLHttpRequest with GET mothod using a php file to check it can make mysql server login. in my machine localhost it works great but in server host i got this error :

Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

I read a lot fix solutions try many things, even edit the .htacess server file, but unfortunaly error always remains!

here is the html code:

<html>
<head>
<script>
   function testconnection(){
      xhttp = new XMLHttpRequest();
      xhttp.open("GET", "PDOconnection.php", true);
      xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      xhttp.setRequestHeader('Access-Control-Allow-Methods','*');
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          alert(this.responseText);
          var result=JSON.parse(this.responseText); 
          console.log(result[0]+" "+result[1]+" "+result[2]);
   
          if (result[0]=='0'){
             alert("Não existe ligação ao Servidor!");
            }       
          if (result[0]=='1'){
             alert("Connection com Sucesso ao Servidor!");
            }                   
        
     } else {
         alert("Problems!!!");
          //alert("xhr status : "+xhttp.readyState+" Status Text: "+xhttp.statusText);
        }
     };

    xhttp.send();
  }

 </script>
</head>
 <body>
  <button onclick="testconnection()">Test Connection</button>
 </body>
 </html>

this is the php file “PDOconnection.php”

?php
  header('Content-type: text/html; charset=UTF-8');
  header("Access-Control-Allow-Origin: *"); 
  header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
          
  $conn = new PDO("mysql:host=SQL306.ezyro.com;dbname=ezyro_31087122_SAGE", "ezyro_31087122","XXXXXXX");
  $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    
    if (!$conn){
        
         $mgs = array("0","Ligação ao Servidor Falhou!!!", "");
         $Txt=JSON_encode($mgs);
         echo "$Txt";
         
        die ("Connection failed: " . $conn_connect_error());
         
    } else {
         $mgs = array("1","Sucesso!!!", "");
         $Txt=JSON_encode($mgs);
         echo "$Txt";
      }

     
     
 $conn=null;

 ?>

Simple zustand store with persist do not get storage in local storage

I create this following zustand store. For now it’s fairly simple, I would like to update functionality later.

import { create } from 'zustand';
import { persist } from 'zustand/middleware';

export interface UserState {
  /* User identity */
  userId: string;
}

export const useUserStore = create<UserState>()(
  persist(
    (): UserState => ({
      userId: crypto.randomUUID(),
    }),
    {
      name: 'myioko-user-storage',
    },
  ),
);

So the idea is for now user will get assigned a uuid, later if user login we will use his stored id, or play as guest with a random uuid that will remain across browser sessions.

But yeah, the localstorage part dont work.

The above keep changing the user id each time I refresh the page, and I dont see anything beeing stored in the localstorage.

Yet it should be working.

I tried 2 browser and in private, nothing change, manually doing localstorage does save the value, but persist doesnt.

Retrieve dynamic page params in layout.tsx – Next.js

I was working on a Next.js 15+ project with TypeScript and I would need to take params from a dynamic route /[slug] in my layouts.jsx.

This is my current code:

import { SidebarProvider } from "@/components/ui/sidebar";
import AuthGuard from "@/components/auth-guard";
import { ReactNode } from "react";
import { AppSidebarTenant } from "@/components/app-sidebar-tenant";
import { getTenantsShortDetails } from "@/lib/tenantDetails";

export default async function TenantLayout({
  children,
  params,
}: {
  children: ReactNode;
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;
  const tenantsData = await getTenantsShortDetails();

  return (
    <AuthGuard>
      <SidebarProvider>
        <AppSidebarTenant tenantSlug={slug} tenants={tenantsData} />
        {children}
      </SidebarProvider>
    </AuthGuard>
  );
}

But, when I do npm run build I keep getting this error from the server:

.../[slug]/page.ts:34:29
Type error: Type '{ params: { slug: string; }; }' does not satisfy the constraint 'PageProps'.
  Types of property 'params' are incompatible.
    Type '{ slug: string; }' is missing the following properties from type 'Promise<any>': then, catch, finally, [Symbol.toStringTag]

I tried several ways that I found here and there online, but nothing, always the same error, even though I think the code is correct.

At the end of it all I tried to ask the AI, but it still couldn’t help me XD.

Some answers here on StackOverflow seem similar to the pattern applied to my code, but I really can’t figure it out.

If anyone has had the same problem and would like to help me solve it, I’d be very grateful.

Thanks in advance.

How to create and manipulate JavaScript Date objects from Brython

I am using Brython without importing the Python standard library.

I would like to write Brython code to do the work of routine date manipulation in JavaScript:

var foo = new Date()
foo.setHours(4)
var time = foo.getTime()

In my searching, I thought I saw that the first line could be approximated in Brython by:

from javascript import Date
foo = Date.new()

However, I ran into trouble trying to call Date.new() (and also new Date() and just Date()) from Brython; the last one returned a string giving the time, without obvious methods of JavaScript Date objects.

Is there a winning approach using Brython without the Python standard library to handle e.g. routine creation and manipulation of JavaScript Date objects, or should I use Brython with the standard library and use Python’s datetime facilities?

How to make a variable content format on a page for the user?

Need advice from experienced programmers on how best to organize variable content on a blade template page in Laravel, where data is received.

The task is as follows. Make the ability for users to change the content display format on the page using buttons, card (default), or a table, without re-requesting Ajax on the server.

Thus, data comes from the controller, we sort through it and output it in the card format.

Here are my thoughts:

  1. The simplest thing that comes to mind is to immediately make a blade layout on the page in two formats, cards and tables, and simply hide and display what you need using js. (But it seems to me that this is not very correct, although I may be wrong)
  2. This is to somehow record the data from the controller, maybe in local storage, or something else, and rebuild the layout on request from this data…

Tell me in which direction to go, who has done something similar, maybe they will suggest a more correct or effective option.

I use jq.

JavaScript DOM manipulation in the Browser

I am trying to get an element, and element’s fontSize property and update the size with keypresses. I press the up’ArrowUp’ and down ‘ArrowDown’ but nothing happens, the fontSize property does not change. Could someone please explain to be why the eventListener is not working? Thank you in advance.

let example = document.querySelector('exampleElement')
let exampleSize = getFontSize(example);


function getFontSize(element) {
    return parseInt(window.getComputedStyle(element).fontSize);
}

example.addEventListener('keydown', (event) => {
        switch(event.key){
            case 38:
            example.style.fontSize = `${exampleSize + Math.ceil(exampleSize * .10)}px`;
            break;
            case 40: 
            ballon.style.fontSize = `${exampleSize - Math.ceil(exampleSize * .10)}px`;
            break;
        }
});

I have tried to rewrite this function for well over two hours now, any help would be greatly appreciated! I am expecting the html element to ‘grow’ when the up arrow button on the key board is pressed and the inverse when the down arrow button is pressed.