Vuejs Asynchronous Components’ Refs are not reactive as props to child components (only happens in production)

I’m using VueJS async components, I’m storing them in refs but it seems like these refs are never created as reactive refs in production.

My app asynchronously loads up certain components where they are needed. I have created a map of the components along with what I would like their ref to be as such:

const componentsMap = {
    header: {
        component: defineAsyncComponent(() => import("./components/header-panel.vue")),
        ref: "header_panel",
    },
    hero: {
        component: defineAsyncComponent(() => import("@/views/Editor/components/hero/hero-panel.vue")),
        ref: "hero_panel",
    },
};

Usage of these async components with the built-in dynamic <component /> is as such:

<component :is="currentComponent" :ref="currentComponent.ref" />

Having previously defined the refs which will store each of the component instances once they are loaded:

const header_panel = ref<any>(null);
const hero_panel = ref<any>(null);

I expect to then be able to access these refs by passing them to a child component:

<ChildComponent :header_panel="header_panel" :hero_panel="hero_panel" />

I then expect to be able to use these two panels in ChildComponent.

It works as expected in development, once the asynchronous components have been loaded, the child component gets the updated prop and it stops being null, then it can be used.

In production, the props of the ChildComponent don’t get updated once an async component has been fetched, I used a watcher to check and it appears it never gets instantiated as a reactive variable.

Is My Use of JavaScript import Statements Correct? [closed]

I’ve read the MDN documentation, but it feels like a lot of information, and as a non-native English speaker, I’m not sure if I’ve understood everything correctly. What I want to do is have a main.js file that imports other JavaScript files, such as lightbox.js, clipboard.js, etc. Is this approach correct?:

main.js:

import "./custom";
import "./lightbox"

The files are in the same folder as the main.js file. I’m using ESBuild, and everything seems to be working, but I’m not sure if I did it correctly. I often see import statements with the from keyword, but in my case, I’ve imported the whole files directly, which is what I actually want. Is this the right approach?

How to customize HTML report file name in Playwright

I’m trying to customize the Playwright’s HTML report file name.

I’ve tried both fileName and outputFile settings but no luck.
I have to mention that when I set outputFolder it changes the folder accordingly.

import { defineConfig } from '@playwright/test';

export default defineConfig({
  reporter: [
    [
      "html",
      {
        fileName: "test-results.html", // Not working
        outputFile: "myFile.html", // Not working
        outputFolder: "myFolder", // Working
      },
    ],
});

In other reporters such as json or junit these settings works just fine:

import { defineConfig } from '@playwright/test';

export default defineConfig({
  reporter: [
    ['json', {  outputFile: 'test-results.json' }] // Working
  ],
});

I couldn’t find anything useful in Playwright Reporters Docs regarding this problem.

Change TableContainer default theming chakra ui

I’m using chakra ui’s TableContainer with the following style:

<TableContainer p="8" m="8" bg="white" border="6px solid" borderRadius="xl" borderColor="white" boxShadow='base'>

I want to add a default theme to it, I have tried the following:

I have this file tableContainer.js:

const TableContainer = {
    baseStyle: {
      p: "8",
      m: "8",
      bg: "white",
      border: "6px solid",
      borderRadius: "2xl",
      borderColor: "white",
      boxShadow: "base",
    },
  }
  
export default TableContainer

In my index.js I have this to set the default usage:

import { extendTheme } from "@chakra-ui/react"
import TableContainer from ".tableContainer"

const overrides = {
    components: {
        TableContainer
    }
}

export default extendTheme(overrides)

My app.js has the following line it it as well:

<ChakraProvider theme={theme}>

Then just calling <TableContainer><TableContainer/>

But my styling is not applying.

Any advice would be greatly appreciated?

How can I execute a function if a user cancels a download in browser during the operation in JavaScript?

I’m using the following JavaScript function to initiate a file download:

function save(object, mime, name) {
  var a = document.createElement('a');
  var url = URL.createObjectURL(object);
  a.href = url;
  a.download = name;
  a.click();
}

This function creates a download link and simulates a click to start the download process. However, I want to run a specific function if the user cancels the download or closes the tab during this operation.

Cancel Button

Is there a way to detect if the download is canceled or interrupted so that I can execute a function or handle the situation appropriately? If not, is there a workaround to achieve this?

I understand that JavaScript in the browser has limited access to the download status after the user initiates it, but any suggestions or workarounds would be greatly appreciated!

Jquery each SVG element

Here is my problem: I use the WordPress image map pro plugin to generate plans with clickable areas in SVG. When the page loads, the HTML code is generated. I want to loop in jquery on the SVG elements generated by the plugin in order to be able to retrieve their data-title that I must use later. But it does not find me any occurrence. On the other hand, if I tell it to loop as soon as I click on an area, it retrieves all the elements. I do not understand. I notice that the plugin’s JS file is loaded at the end. By creating a JS file that loads after the plugin’s, it does not work.

website url : https://preprod.meriadeck.com/liste-boutiques-meriadeck/

code not working :

     jQuery(document).ready(function(){
        jQuery( ".imp-objects" ).each(function() {
            let valueObjectMapSingleProduct = jQuery(this).attr('data-title');
            console.log("toto");
        });
    });

code working :

 jQuery('.liste-boutique-nav li').click(function(){
        jQuery( ".imp-objects" ).each(function() {
            let valueObjectMapSingleProduct = jQuery(this).attr('data-title');
            console.log("toto");
        });

    });

Thanks for your help !

Nico

I tried to load the code in the footer after calling the plugin’s js file.
When trying to use the each loop on SVG elements independent of the plugin, everything works but as soon as it comes to SVG elements generated by the plugin, it doesn’t work. I have the impression that an action (click for example) is needed for it to work.

How to download videos from YouTube using a browser bookmark

I have internet filtering on my computer and the filtering company blocks all video downloads from YouTube and it only leaves the option to watch. The question is whether someone can bring or create a javascript code or another suitable language that I will put in a bookmark in the browser and when I click on the bookmark the video will be reduced to the highest quality or it will be Some options. It is very important that the code does not work through another server, because of course the other servers are blocked. It must be that the code itself downloads the file. Thank you very much.

I tried several times to download the video and could not use software

No cookie in request headers from tRPC client received at tRPC server

I try to get cookies of the request from tRPC client using this context.ts of tRPC server:

import { IncomingMessage, ServerResponse } from 'http';
export async function createContext({ req, res }: { req: IncomingMessage; res: ServerResponse }) {

    console.log(req.headers);
    
    le user = null;
    return {
        user,
    };
}
export type Context = Awaited<ReturnType<typeof createContext>>;

tRPC server is hosted under http://localhost:2022

and I send requests to it from tRPC client at http://localhost:3000 like

import { createTRPCProxyClient, httpBatchLink } from '@trpc/client';
const trpcClient = createTRPCProxyClient<AppRouter>({
    links: [
        httpBatchLink({
            url: 'http://localhost:2022',
            fetch(url, options) {
                return fetch(url, {
                  ...options,
                  credentials: 'include',
                });
            },
        }),
    ],
});
export default trpcClient;

and there are cookies with HttpOnly and SameSite=Lax at http://localhost:3000, but they are not sent to tRPC server as I don’t see any cookie in headers in console.log(req.headers), what I see is only

{
  host: 'localhost:2022',
  connection: 'keep-alive',
  'content-type': 'application/json',
  accept: '*/*',
  'accept-language': '*',
  'sec-fetch-mode': 'cors',
  'user-agent': 'node',
  'accept-encoding': 'gzip, deflate'
}

I use standalone tRPC server with working cors like

createHTTPServer({
    middleware: cors({
        origin: 'http://localhost:3000',
        credentials: true
    }),
    router: appRouter,
    createContext,
}).listen(2022);

when I go at http://localhost:2022 in browser, I see the cookies

how to receive cookies at the tRPC server?

JavaScript replaceAll Regex Matches with translated character Code

I want to use the regex capture group to translate UTF-16 values in an ID.

var x = "ELEMENTT_x5F_GS1_x5F_MARKETING_x5F_CLAIM__x3B__INSTANCE_x3D_3__x3B__LOCALE_x3D_1_"
var regex = /_(x..)_/g;
var replacedID = x.replaceAll(regex, String.fromCodePoint("0" + "$1"));

however this does not appear to fill in the captured value into the string the same way it normally works.
i have tried any which way and it does not seem to recognize the “$1” as replace capture group.

Show/hide one element at the time

I using this script to show/hide content. However, how can I close open elements when opening one?
I tried with something like this, but it’s not working correctly:

// Get siblings
var contentSiblings = document.querySelectorAll('.content');

// close them before opening new one
if (contentSiblings) {
        contentSiblings.forEach((elem) => {
                if (elem.classList.contains('is-visible')) {
                        hide(elem);
                }
        });
}

// Show/hide filter content
var show = function (elem) {
    elem.classList.add('is-visible');
};

// Hide an element
var hide = function (elem) {
    elem.classList.remove('is-visible');
};

// Toggle element visibility
var toggle = function (elem) {

    // If the element is visible, hide it
    if (elem.classList.contains('is-visible')) {
        hide(elem);
        return;
    }

    // Otherwise, show it
    show(elem);
};

// Listen for click events
document.addEventListener('click', function (event) {

    // Make sure clicked element is our toggle
    if (!event.target.classList.contains('btn')) return;

    // Prevent default link behavior
    event.preventDefault();

    // Get the selected content
    var content = document.querySelector(event.target.hash);
    if (!content) return;

    // Toggle the content
    toggle(content);

}, false);
.content {
    display: none;
    opacity: 0;
    transition: opacity .15s linear;
}

.content.is-visible {
    display: block;
    opacity: 1;
}
<a class="btn" id="btn-one" href="#one">Button one</a>
<a class="btn" id="btn-two" href="#two">Button two</a>
<div class="content" id="one">Content one</div>
<div class="content" id="two">Content two</div>

How to improve page speed

I’m running an e-commerce site, FominSoap.com, which is built on WooCommerce. The site has numerous product pages, each with several high-quality images. While the images are essential for showcasing our products, they’re significantly affecting the page load speed.

I have installed wp rocket and light speed cache to optimize speed but I am unable to improve it

In JavaScript, how to find Strong number & Perfect number? [closed]

In JavaScript, how to find Strong number & Perfect number?
Some foundational questions:
how do we extract digits in Javascript using while loop?

How do we find out STRONG NUMBERS or not using while loop?

What is a nested while loop?

thank you

Definition: Strong numbers are the sum of factorials are same as the original number(eg.145)
Perfect numbers are the sum of the proper divisors make the sum(eg.28)

About Strong numbers, the steps are:

  1. Extract digits
  2. Factorials
  3. Sum up the factorials
  4. Check whether the sum is the same as the original number

Need to know the programming.

thx

Streaming chunks of video using javascript

Using JavaScript I am trying to receive chunks of video and display them in a html video tag. but in the code I have, after displaying 3 or 4 chunks, it gets stuck and doesn’t move to the next chunk.
can you help me with this?


// Fetch an encrypted video chunk from the server
async function fetchChunk(chunkIndex) {
    const url = `http://localhost/video/encrypted_chunks/chunk_${chunkIndex}.enc`;
    try {
        const response = await fetch(url);
        if (response.ok) {
            return await response.arrayBuffer();
        } else {
            console.error(`Failed to fetch chunk ${chunkIndex}: Status ${response.status}`);
            return null;
        }
    } catch (error) {
        console.error(`Error fetching chunk ${chunkIndex}:`, error);
        return null;
    }
}

function appendBuffer(sourceBuffer, decryptedData) {
    return new Promise((resolve, reject) => {
        function onUpdateEnd() {
            sourceBuffer.removeEventListener('updateend', onUpdateEnd);
            resolve();
        }

        if (sourceBuffer.updating) {
            sourceBuffer.addEventListener('updateend', onUpdateEnd, { once: true });
        } else {
            sourceBuffer.appendBuffer(new Uint8Array(decryptedData));
            resolve();
        }
    });
}

// Finalize the MediaSource stream
function finalizeStream(mediaSource) {
    if (mediaSource.readyState === 'open') {
        mediaSource.endOfStream();
    }
}

// Main function to handle video streaming
async function streamVideo() {
    const mediaSource = new MediaSource();
    const video = document.getElementById('videoPlayer');
    video.src = URL.createObjectURL(mediaSource);

    mediaSource.addEventListener('sourceopen', async () => {
        const sourceBuffer = mediaSource.addSourceBuffer('video/webm; codecs="vp8, vorbis"');
        let chunkIndex = 1;

        const filename = 'sample-2.webm'; // Replace with the actual filename
        const { key, iv } = await calculateKeyIv(filename);

        // Function to handle fetching, decrypting, and appending chunks
        async function handleChunks() {
            try {
                while (true) {
                    if (sourceBuffer.updating) {
                        await new Promise(resolve => sourceBuffer.addEventListener('updateend', resolve, { once: true }));
                    }

                    const encryptedData = await fetchChunk(chunkIndex);
                    if (!encryptedData) break; // No more data

                    const decryptedData = await decryptChunk(encryptedData, key, iv);
                    await appendBuffer(sourceBuffer, decryptedData);

                    chunkIndex++;
                }

                // Wait for buffer to be done updating before finalizing
                if (!sourceBuffer.updating) {
                    finalizeStream(mediaSource);
                    createWatermark();
                }
            } catch (error) {
                console.error('Error processing chunks:', error);
            }
        }

        // Start processing chunks
        handleChunks();
    });
}

// Call the streamVideo function to start streaming
streamVideo();

I think the problem is probably with the buffer but I’m new to JavaScript and I haven’t been able to debug it!

We are using JavaScript constructor class to set data attribute values for ajax call

Below is the code snippet

”’

var FilterTest = class { 
constructor() { 
  this.data_scope= $("#ID").data('scope');
}; 
getAttrs() { 
 var Opts = {data_scope: this.data_scope};
 Opts['attr2'] = "ABC";
 return Opts;
 }  
}

Obj = new FilterTest();

$.ajax({
 url: URL,
 data: Obj.getAttrs(),
 dataType: 'json'
}).done

on live site that opts return empty hash in ajax call. This issue comes for some users

Constructor class return empty hash in some browsers

How to prevent wp_localize_script from localize the ajax URL in the array?

Currently in my WordPress plugin, I use wp_localize_script to pass data from PHP to JS, as below:

    wp_localize_script($this->plugin_name, 'MyObj', array(
        'ajax_url' => admin_url('admin-ajax.php'),
    ));

It works properly in English post with a shortcode of the plugin. However, in the Chinese post with the same shortcode, it does not. After tracing the data, I find in the Chinese post, the ajax_url will be added a language slug.

For example, if the English post is https://www.example.com/blogs/jpg-to-png/, then the ajax_url will be https://www.example.com/blogs/wp-admin/admin-ajax.php, which is correct.

But in the Chinese version, https://www.example.com/zh-CN/blogs/jpg-to-png/, then ajax_url will also be changed to https://www.example.com/zh-CN/blogs/wp-admin/admin-ajax.php, which is not desired.

How to prevent this? I try to pass the root_url, admin_url, but wp_localize_script will always add the language slug for the Chinese post. How to keep the data intact when passing it from PHP to JS?