Arabic “Majed” voice randomly not showing in SpeechSynthesis (TTS) API

Browsers with the SpeechSynthesis provide Arabic through one voice “Majed” as ar-001 or ar-SA and it usually works on all browsers except ones that use WebKit I noticed.
On Webkit based browsers, especially iPhones & iPads, that specific voice doesn’t appear randomly sometimes! I am trying to figure out how can I make sure that an Arabic language can always be used?

Here’s a codepen where you can try it yourself. For the SAME device, when I go to that page the first time, Majed appears, but it didn’t appear a few times later. You can also just open a developer console on any page and put in window.speechSynthesis.getVoices() and the first element in the list should be arabic (majed)

This is what it looks like on a Mac using Safari sometimes, where Arabic does appear above Daria as it does appear correctly with other browsers and operating systems
Screenshot showing Arabic
This is what it looks like on an iPhone/iPad sometimes, where the Arabic doesn’t appear at all when it should appear above “Daria”:
Screenshot from iPhone not showing Arabic

Show / hide div using checkbox and addEventListener click event

The following javascript works but not in my application as a product filter. In my case, clicking the checkbox displays the div but unchecking does not hide the div. Applying, onclick event to the checkbox is also not doable. Is it possible to have two addEventlistener ‘click’ events, one for opening and one for closing?

const check = document.getElementById("checkbox-id");
if (check) {
    check.addEventListener('click', event => {
    this.event = event;
if (check.checked) { document.getElementById("showDiv").style.display = "block"; } 
else { document.getElementById("showDiv").style.display = "none"; }
});
}
#showDiv{display:none;width:100%;background-color:#252525;color:#ffffff;}
<form>
<input class="input" type="checkbox" id="checkbox-id">
</form>
<div id="showDiv">Show / hide</div>

I have tried the following (and others) but I have not been able to hide the box after being revealed. Just know, the click event is the only way that has produced a result. Happy to provide any other info if needed. TY

const general = document.getElementById("checkbox-id");
  const checkOpen = () => {document.getElementById("showDiv").style.display = "block";}
  const checkClosed = () => {document.getElementById("showDiv").style.display = "none";}
if (element) {
    element.addEventListener('click', event => {
    this.event = event;
checkOpen();
checkClosed();
});
}

Chart.js barplot keeps getting bigger without stopping

Just like the title says. I have a chart that when I open the page it keeps getting bigger and bigger and bigger. I genuinely don’t understand why because I have another plot pretty similar with the same html/css.
Here’s the chart:

new Chart(
        document.getElementById("weeklyWatched_id"),
        {
            type: 'bar',
            data: {
                labels: filteredData.map(row => row.week_number),
                datasets: [
                    {
                        data: filteredData.map(row => row.weekly_quantity),
                        backgroundColor: 'rgb(255, 0, 0)',
                        borderWidth: 0
                    }
                ]
            },
            options: {
                title: {
                    display: true,
                    text: 'Data Semanal',
                    fontColor: '#131313', // Change title color
                    fontFamily: 'Arial' // Change title font to Arial
                },
                legend: { display: false },
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    yAxes: [{
                        ticks: { display: false, beginAtZero: true }, // Remove y-axis text
                        gridLines: { display: false } // Remove y-axis grid lines
                    }],
                    xAxes: [{
                        ticks: { display: false }, // Remove x-axis text
                        gridLines: { display: false } // Remove x-axis grid lines
                    }]
                },
                tooltips: {
                    callbacks: {
                        label: function(tooltipItem, data) {
                            const value = tooltipItem.value;
                            const weekNumber = data.labels[tooltipItem.index];
                            const weekRange = filteredData[tooltipItem.index].week_range;
                            const peliText = value <= 1 ? ' Peli' : ' Pelis';
                            return `${value}${peliText}n${weekNumber} Sem.n${weekRange}`;
                        }
                    },
                    displayColors: false
                },
                layout: { padding: 20 }
            }
        }
    );

Custom VueJS ESLint rule for parsing section does not work

I have the following config, custom rule, and template:

export default [
  {
    files: ['**/*.{js,vue}'],
    languageOptions: {
      ecmaVersion: 'latest',
      sourceType: 'module',
      parser: vueEslintParser,
    },
    plugins: { example: exampleRules },

    rules: {
      'example/warn-something': 'warn',
    }
  }
]

export default {
  meta: {
    type: 'suggestion',  // Can be 'problem', 'suggestion', or 'layout'
    docs: {
      description: 'find a node with attribute class',
      category: 'Best Practices',
      recommended: false,
    },
    fixable: null, // This rule doesn't have an auto-fix.
    schema: [], // No options for this rule.
  },
  create (context) {
    // return context.parserServices.defineTemplateBodyVisitor(context, {
    return {
      'VAttribute[name="class"]' (node) {
        console.log('found VAttribute with class attribute. node:', node)

          context.report({
            node,
            message: 'found VAttribute with class attribute',
          })
      }
    }
  }
}

<template>
  <div :class="['style-dark']"></div>
</template>

The parser does not parse the <template> section. I’d like to find out why 'VAttribute[name="class"]' (node) is not called.

a) Is there a way to set breakpoints and debug rules? I haven’t found anything online about it.

b) Is the parser configured correctly? The docs say to use a string parser: 'vue-eslint-parser', but it errors. Other sources say to use an import parser: vueEslintParser.

c) How to get access to parserServices? I saw this used a few ways but it ends up undefined here.

Any help appreciated.

Binding scalar data to HTML element – JavaScript Proxies

I may be guilty of a bit of an XY question here, but I’m doing this out of theoretical interest rather than any immediate need.

My goal is, ultimately, to build a lightweight framework that allows me to bind scalar data to a property of an HTML element such that the property updates “automagically” whenever the value changes.

I’m trying to come up with the most syntactically elegant way to do this, that puts IDE code-completion and developer convenience at the forefront.

I’m aware of Proxies, and I’ll get to that in a moment. My challenge is really in the syntactic sugar I’m trying to create, so come along for the ride – I can always fall back to many tried-and-true approaches but I’m hoping for something more magical.

Let’s assume I already have a nice little framework that wraps DOM Nodes with additional functionality, and can Proxy the DOM Node if needed.

The ultimate data-binding implementation from a syntax/API perspective would be:

let someVar = "foo"
let someElement = MyFramework.getById("some-div"); // returns a proxied HTMLElement with additional methods added
someElement.bind("innerText", someVar);

// later...
someVar = "bar"; // someElement.innerText automatically updates

Now, before you freak out, I’m aware that this will simply not work, as there’s no way to proxy a Primitive, so I’m happy to wrap this in a state object that CAN be proxied.

let state = MyFramework.createState(); // returns a proxy of the State object
state.someVar = "foo";
let someElement = MyFramework.getById("some-div");
someElement.bind("innerText", state.someVar);

This is where it gets tricky, because I actually need to access the object key “someVar” within my .bind() function, but I’m just getting the value of state.someVar.

I CAN set a proxy within my createState() function which can trap the getter and instead of returning the value, returns the property name like this:

MyFramework.createState = function(initialProps = {}){
  let proxy = new Proxy(initialProps, {
     get(target, prop, receiver){
        return prop;
     }
   }

   return proxy;
}

…but then I can’t really make use of the variable, because I don’t know how to make my “get” trap conditional – ie, only return the prop when being accessed from within the bind() function, otherwise just return Reflect(...arguments).

What I’m hoping to avoid is the following:

someElement.bind("innerText", state, "someVar");

Similarly,

someElement.bind("innerText", state, state.someVar)

just seems redundant and prone to user error.

Alternatively I’d be open to:

state.someVar.bind(someElement, "innerText");

but that won’t work (that I can think of) because someVar is still a scalar (primitive) and therefore can’t get any custom properties (like .bind() attached).

I was thinking I could intercept the first accessor (state.someVar), Proxy THAT and trap its get to handle the non-existent “bind” function, but again, without being able to do that contextually, the user would then never be able to use state.someVar in a simple scalar context, and we’d have to resort to something ugly like state.someVar.set("new val") and state.someVar.get(), and that defeats the purpose of my inquiry.

I think I’ve about exhausted my level of JS internals knowledge and wondering if there’s something obvious I’m missing.

And I should point out that if you are tempted to say “well, you’re asking about Y but really you should approach X differently” I appreciate that, but only if there really is NO way to achieve the syntactic elegance I’m looking for. Like I said, there are plenty of documented ways to achieve this – I’m trying to see if I can do it fancier.

Template parsing of ESLint rule for VueJS does not work

The following questions are related to a single issue of the parser not seemingly parsing. Why this is, is unknown, and I’m looking for ways to debug it or get it to work.

What is the correct way to configure eslint.config.js? The documentation shows parser: 'vue-eslint-parser', but in my case got the following error

TypeError: Key “languageOptions”: Key “parser”: Expected object with parse() or parseForESLint() method.

There are other recommendations to use an import instead. What is the proper way?

import exampleRules from './example/eslint-plugin-rules.js'
import vueEslintParser from 'vue-eslint-parser'

export default [
  {
    files: ['**/*.{js,vue}'],
    languageOptions: {
      ecmaVersion: 'latest',
      sourceType: 'module',
      parser: vueEslintParser,
    },
    plugins: { example: exampleRules },

    rules: {
      'example/warn-something': 'warn',
    }
  }
]

Below is a simplified custom rule and template.

Is there a way to step through, and debug rules in say VSCode? I’d like to see console.log statements or stop at a breakpoint but have not seen anything documented about it.

export default {
  meta: {
    type: 'suggestion',  // Can be 'problem', 'suggestion', or 'layout'
    docs: {
      description: 'find a node with attribute class',
      category: 'Best Practices',
      recommended: false,
    },
    fixable: null, // This rule doesn't have an auto-fix.
    schema: [], // No options for this rule.
  },
  create (context) {
    // return context.getSourceCode().parserServices.defineTemplateBodyVisitor(context, {
    return {
      'VAttribute[name="class"]' (node) {
        console.log('found VAttribute with class attribute. node:', node)
      },
    }
  }
}

<template>
  <div :class="['style-dark']"></div>
</template>

Why does create(context) sometimes return an object of methods, and other times return the result from defineTemplateBodyVisitor(context, {}) for template parsing?

Appreciate any answers or advice.

How to configure, develop and debug ESLint rule for VueJS

I’d like to create a custom ESLint rule for Vue, which runs inside a <template> tag.

The following questions are related to a single issue of the parser not seemingly parsing. Why this is, is unknown, and I’m looking for ways to debug it or get it to work.

a) What is the correct way to configure eslint.config.js? I saw the documentation and many examples with parser: 'vue-eslint-parser', but in my case got the following error

TypeError: Key “languageOptions”: Key “parser”: Expected object with parse() or parseForESLint() method.

However, also saw recommendations to use an import instead, for those where using a string caused an error. Here’s the config below. Should this be done differently?

import exampleRules from './example/eslint-plugin-rules.js'
import vueEslintParser from 'vue-eslint-parser'

export default [
  {
    files: ['**/*.{js,vue}'],
    languageOptions: {
      ecmaVersion: 'latest',
      sourceType: 'module',
      parser: vueEslintParser,
    },
    plugins: { example: exampleRules },

    rules: {
      'example/warn-something': 'warn',
    }
  }
]

b) How are custom rules usually developed? I did the tutorial which worked fine. I also saw RuleTester, which is good for testing a rule. But is there a way to develop, step through, and debug in say VSCode? Is there a way to see console.log statements or stop at a breakpoint?

Below is a simplified custom rule with a minimal method for handling an element with a class attribute. The context in create(context) does not seem to have parserServices, which are used by a lot of the rules in eslint-plugin-vue. I’ve seen this create method developed a couple ways: one returns an object of methods, another returns the result from defineTemplateBodyVisitor(context, {}). What is the difference?

export default {
  meta: {
    type: 'suggestion',  // Can be 'problem', 'suggestion', or 'layout'
    docs: {
      description: 'find a node with attribute class',
      category: 'Best Practices',
      recommended: false,
    },
    fixable: null, // This rule doesn't have an auto-fix.
    schema: [], // No options for this rule.
  },
  create (context) {
    // return context.getSourceCode().parserServices.defineTemplateBodyVisitor(context, {
    return {
      'VAttribute[name="class"]' (node) {
        console.log('found VAttribute with class attribute. node:', node)
      },
    }
  }
}

c) Below is a simplified Vue <template>. I believe the method 'VAttribute[name="class"]'(node) above should be invoked when traversing the AST. Does that look correct?

<template>
  <div :class="['style-dark']"></div>
</template>

I tried a slightly more complicated custom rule and template but it doesn’t seem to work, and developing/debugging does not seem straightforward. Appreciate any answers or advice.

Failed to fetch –

I have read How do I upload a file with the JS fetch API?

and

Getting “TypeError: Failed to fetch” when the request hasn’t actually failed

I have some javascript that sends a javascript object to WebApi backend, and it works!

I am now trying to use the same code to upload a file.

This is what I’m trying to upload to (my C# WebApi 2)

public async Task UploadImage([FromBody] object o)
{
    //do something
}

and the javascript

const file = inputTypeFile.files[0];

async function withData(url = '', data = {}, verb, success) {

const response = await fetch(url, {
     method: verb, 
     mode: 'cors', 
     cache: 'no-cache',
     credentials: 'same-origin', 
     headers: getHeader(),
     referrerPolicy: 'no-referrer', 
     body: file
 }).catch(function (e) {
     errorHandler(e);
 });

I always get a failure

Failed to fetch at withData

If I change the value of file to a valid json object, like {some:123} then it works fine.

Variable breaking script [closed]

If I add a vairable the bot message breaks.

This is the code I have right now

 await channel.send({
        embeds: [{
            color: categories.length > 0 ? CATEGORY_COLORS[categories[0]] : 0x0099ff,
            title: `${article.title} `,
            url: article.link,
            author: {
                icon_url: `attachment://image.png`,
                name: source
            },
            description: `${cleanDescription.substring(0, 250)}${cleanDescription.length > 250 ? '...' : ''}nn${categories.map(cat => `${cat}`).join(' | ')}nPing: <@&${GLOBAL_PING_ID}> ${categoryPings}n`,
            fields: embedFields,
            footer: {
                text: `Made by Genius74o`
            },
            image: {
                url: thumbnailUrl || '' 
            },
        }],
        files: [{
            attachment: `./images/image.png`
        }]
    });

But if i change image.png to a variable it breaksThis is the image without the vairable
This is the image with the varaible

It is the right parth to the image

Please help, thanks in advance

Webpack: Dynamically generate a file for file-loader that includes requires

I’m working with Webpack 4, and what I am trying to do is conceptually simple: I want to use file-loader with dynamically-generated content that can require other modules, instead of a static file.

In a little more detail, I want to:

  1. Generate an HTML page using Pug that requires a file dynamicfile.xml using file-loader. For example, the line link(name='search' href=require('./dynamicfile.xml')) should generate something like <link name="search" href="/dynamicfile.58ef.xml">, and a file dynamicfile.58ef.xml should be written to disk.
  2. The actual contents of dynamicfile.58ef.xml should be generated by a template or JS module, where part of it requires another module using file-loader. For example, if the template is in EJS syntax and looks like <sometag file="<%= require('./image.png') %> />", then the final contents of dynamicfile.58ef.xml should look something like <sometag file="/image.8a4e.png" />.

Note that I am using Webpack 4, not Webpack 5, because the project I am working with uses Webpack 4, and the migration to 5 would be very complicated and time-consuming.

I have already Googled and ChatGPT’ed the issue thoroughly and have not found a solution.

I tried generating the xml file dynamically with an EJS loader and then converting it to a string with apply-loader. In terms of the dynamically generated content, it gives my exactly what I want, if I require it inline in the HTML file. However, if I try to load it using file-loader in the HTML file, it always writes the source code of the template to the external xml file, instead of the dynamic content. So, I don’t understand why Webpack doesn’t evaluate the module’s code before writing it to the file (or how to do it). I think I have a conceptual misunderstanding that someone more knowledgeable can clear up for me.

I have also tried using val-loader@2, but it leads to exactly the same problem: file-loader writes out the source code generated by val-loader that would evaluate the module.

How to use an HTMLAudioElement controls to play the content of an AudioBuffer?

Considering the requirement of this function signature:

function initPlayer(player: HTMLAudioElement, buffer: AudioBuffer): void;

I’m looking for a way to control the AudioBuffer playback using the provided HTMLAudioElement.

I see plenty of examples using the start() method of a AudioBufferSourceNode, such as

const context = new AudioContext();
const destination = context.createMediaStreamDestination();
const source = context.createBufferSource();
source.buffer = buffer;  // some AudioBuffer instance
source.connect(destination);
source.start(0);

However this only plays the audio, it does not bind it to the player’s controls; play, pause, stop, seek, etc. have no effect.

There are also other solutions, using a Blob, or an ArrayBuffer from some downloaded mp3 file, for example. However the provided AudioBuffer is the only value I can work with, here.

I have looked at creating a audio/wav (or audio/mp3) Blob, but I can’t wrap my head around the idea that AudioBuffer can’t be directly played from a HTMLAudioElement.

Why is that, and what’s the proper solution to control the playback using the browser media player?

Script inside Template won’t execute on Import

I am learning about templates, custom elements, shadow DOM, etc. Here, I like to utilize Swiper lib to create custom element that i can compose as i wish in the future. It works when everything is one file as follows:

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

<head>
  <meta charset="utf-8" />
  <title>Swiper demo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1" />

  <template id="TmplCoverflowSwiper">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.css" />
    <style>
      html,
      body {
        position: relative;
        height: 100%;
      }

      body {
        background: #eee;
        font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
        font-size: 14px;
        color: #000;
        margin: 0;
        padding: 0;
      }

      .swiper {
        width: 100%;
        padding-top: 50px;
        padding-bottom: 50px;
      }

      .swiper-slide {
        background-position: center;
        background-size: cover;
        width: 300px;
        height: 300px;
      }

      .swiper-slide img {
        display: block;
        width: 100%;
      }
    </style>
    <div class="swiper mySwiper">
      <div class="swiper-wrapper">
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-1.jpg" />
        </div>
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-2.jpg" />
        </div>
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-3.jpg" />
        </div>
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-4.jpg" />
        </div>
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-5.jpg" />
        </div>
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-6.jpg" />
        </div>
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-7.jpg" />
        </div>
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-8.jpg" />
        </div>
        <div class="swiper-slide">
          <img src="https://swiperjs.com/demos/images/nature-9.jpg" />
        </div>
      </div>
      <div class="swiper-pagination"></div>
    </div>
    <script>
       (async () => {
          // <!-- Swiper JS -->
          const { Swiper } = await import("https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.mjs");
          console.log('swiper-bundle imported...')

          // <!-- Initialize Swiper -->
          var swiper = new Swiper(".mySwiper", {
            effect: "coverflow",
            grabCursor: true,
            centeredSlides: true,
            slidesPerView: "auto",
            coverflowEffect: {
              rotate: 50,
              stretch: 0,
              depth: 100,
              modifier: 1,
              slideShadows: true,
            },
            pagination: {
              el: ".swiper-pagination",
            },
          });

          console.log('swiper initiated...');
        }
        )();
    </script>
  </template>

  <script>
    class CoverflowSwiper extends HTMLElement {
      constructor() {
        super(); // always call super() first
      }

      /** Custom Component Reactions **/
      connectedCallback() {
        console.log("Coverflow-Swiper  connected to page");

        //set initial state of visiable
        this.visible = this.hasAttribute('visible');

        //make deep copy of the template and import into the current document
        let tmpl = document.querySelector("#TmplCoverflowSwiper");
        let newNode = document.importNode(tmpl.content, true);

        // document.getElementById("PCCoverflowSwiper").appendChild(newNode);
        this.appendChild(newNode);
      }
    }

    //link custom element w/ JS class
    customElements.define("pc-coverflow-swiper", CoverflowSwiper);
 
  </script>

</head>

<body>
  <h1>Making Swiper Web Component</h1>
  <pc-coverflow-swiper id="PCCoverflowSwiper">
  </pc-coverflow-swiper>
</body>
</html>

However, i like to keep things separate and when i move out all the code pertained to my custom element into a separate file that is imported in the main file, suddenly the JS script part of the template scope won’t execute and i cann’t seem to understand why it is so, just by removing into separate file?

The main file containing custom element tag while stripped out the rest into file tmpl-swiper.html and imported here in the head here:

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

<head>
  <meta charset="utf-8" />
  <title>Swiper demo</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1" />

    <!-- include the polyfill for web components. This must precede imports -->
    <script src="../polyfills/webcomponents-lite.js"></script>

    <!-- import our template from an external file -->
    <link rel="import" href="tmpl-swiper.html" id="tmplCoverflow">
</head>

<body>
  <h1>Making Swiper Web Component</h1>
  <pc-coverflow-swiper id="PCCoverflowSwiper">
  </pc-coverflow-swiper>
</body>
</html>

Here is the imported template file taken out from the main file into separate file all pertained to the custom element with name tmpl-swiper.html:

html,
body {
position: relative;
height: 100%;
}

  body {
    background: #eee;
    font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
    font-size: 14px;
    color: #000;
    margin: 0;
    padding: 0;
  }

  .swiper {
    width: 100%;
    padding-top: 50px;
    padding-bottom: 50px;
  }

  .swiper-slide {
    background-position: center;
    background-size: cover;
    width: 300px;
    height: 300px;
  }

  .swiper-slide img {
    display: block;
    width: 100%;
  }
</style>
<div class="swiper mySwiper">
  <div class="swiper-wrapper">
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-1.jpg" />
    </div>
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-2.jpg" />
    </div>
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-3.jpg" />
    </div>
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-4.jpg" />
    </div>
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-5.jpg" />
    </div>
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-6.jpg" />
    </div>
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-7.jpg" />
    </div>
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-8.jpg" />
    </div>
    <div class="swiper-slide">
      <img src="https://swiperjs.com/demos/images/nature-9.jpg" />
    </div>
  </div>
  <div class="swiper-pagination"></div>
</div>
<script>
   (async () => {
      // <!-- Swiper JS -->
      const { Swiper } = await import("https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.mjs");
      console.log('swiper-bundle imported...')

      // <!-- Initialize Swiper -->
      var swiper = new Swiper(".mySwiper", {
        effect: "coverflow",
        grabCursor: true,
        centeredSlides: true,
        slidesPerView: "auto",
        coverflowEffect: {
          rotate: 50,
          stretch: 0,
          depth: 100,
          modifier: 1,
          slideShadows: true,
        },
        pagination: {
          el: ".swiper-pagination",
        },
      });

      console.log('swiper initiated...');
    }
    )();
</script>

(function() {
class CoverflowSwiper extends HTMLElement {
constructor() {
super(); // always call super() first
}

  /** Custom Component Reactions **/
  connectedCallback() {
    console.log("Coverflow-Swiper  connected to page");

    //set initial state of visiable
    this.visible = this.hasAttribute('visible');

    //make deep copy of the template and import into the current document
    let tmpl = document.querySelector("#TmplCoverflowSwiper");
    let newNode = document.importNode(tmpl.content, true);

    // document.getElementById("PCCoverflowSwiper").appendChild(newNode);
    this.appendChild(newNode);
  }
}

//link custom element w/ JS class
customElements.define("pc-coverflow-swiper", CoverflowSwiper);

// automatically add the template 
//  to the document that is importing this file so it can be used.

// ownerDocument references this component document being imported
var thisImportDoc = document.currentScript.ownerDocument;

// Get the template from this file, clone it,
// and append it to the importing document.
var tmplNode = thisImportDoc.querySelector('#TmplCoverflowSwiper');

// the "document" keyword here references the "main" document
// (the one that's importing this HTML file)
document.body.appendChild(tmplNode.cloneNode(true));

})();

It imports the file, attaches the template, etc, however. the JS code within the Template tag isn’t executed and i can’t seem to understand the reason. Any help much appriciated. thank you

Why JS don’t show the last message in Telegram? [duplicate]

I am writing a chrome extension. I want to know the user’s last message in a telegram conversation. Here is my code:

js:

function getLastMessage() {
    const messages = document.querySelectorAll('.Message'); 

    if (messages.length > 0) {
        const lastMessage = messages[messages.length - 1];
        const messageText = lastMessage.querySelector('.text')?.innerText || "Нет текста";
        
        alert("Last message:", messageText);
 
    } else {
        alert("There are no messages");
    }
}
document.getElementById('myButton').addEventListener('click', function() {
    getLastMessage();
});

json:

{
    "manifest_version": 3,
    "name": "My Simple Button Extension",
    "version": "1.0",
    "description": "An extension with a single button.",
    "action": {
      "default_popup": "popup.html",
      "default_icon": "icon.webp"
    },
    "permissions": []
  }

This code alert “There are no messages” always but there are messages in chat.
Please, help me.

I can’t find anything in web

A way via functions to reverse the order of an array, using .sort() (need help explaining solution) [duplicate]

I’m new to javascript – I just had a problem that asked me to find a way via functions to reverse the order of an array of years, using .sort(). After flailing for a bit, I checked the answer and received the one below:

const sortYears = arr => arr.sort((x, y) => y - x);

I have no idea how someone would get this, or where the x and y come from.

I tried using sort() and nesting Collections.reverseOrder() as suggested in another answer to a similar question, but kept receiving errors.