Need help regarding Chrome extension dev

I am trying to pass a url on the current tab from contentScript to background and display it in console. But I am alaways getting one error :

Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.

Here is my manifest.json:

{
  "manifest_version": 3,
  "name": "My Extension",
  "version": "1.0",
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["contentScript.js"]
    }
  ],
  "permissions": ["scripting", "activeTab"],
  "background": {
    "service_worker": "background.js"
  }
}

Here is my contentScript.js

// contentScript.js
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  if (message.type === "executeScript") {
    var script = new Script(message.script);
    document.head.appendChild(script);
  }
});
chrome.runtime.sendMessage({
  type: "printToConsole",
  message: "Hello from the content script!",
});

function getActiveTab() {
  chrome.runtime.sendMessage({ type: "getActiveTabRequest" });
}

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  if (message.type === "getActiveTabRequest") {
    const activeTab = message.activeTab;
    console.log("Active tab URL:", activeTab.url);
  }
});

getActiveTab();

Here is my background.js

// background.js
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  if (message.type === "executeScript") {
    var script = new Script(message.script);
    chrome.scripting.executeScript({
      target: { tabId: sender.tab.id },
      func: script,
    });
  }
});
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  if (message.type === "printToConsole") {
    console.log(message.message);
  }
});

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  if (message.type === "sendData") {
    const data = message.data;
    console.log("Received data from content script:", data);
    // Process the data here
  }
});

chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
  if (message.type === "getActiveTabRequest") {
    (async () => {
      const tabs = await chrome.tabs.query({
        active: true,
        currentWindow: true,
      });
      const activeTab = tabs[0];
      chrome.runtime.sendMessage({
        type: "getActiveTabRequest",
        activeTab: activeTab,
      });
    })();
  }
});

What am I doing wrong? Much appreciated!!

error when adding computed property names webpack babel

I tried to replace numbers i am using for to map data with variables so then i can easy update values in one place only.

const allowedViews = {
    32: { /* something */ },
    56: { /* something */ },
    ...
}
module.exports = { allowedViews, ... };

i replaced above with:

const someView = 32;
const someOtherView = 56;
const allowedViews = {
    [someView]: { /* something */ },
    [someOtherView]: { /* something */ },
    ...
}

module.exports = { allowedViews, ... };

After this change i am getting following error:

Uncaught Error: ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: 83305

babel config:

{
    "presets": ["@babel/preset-env", "@babel/preset-react"],
    "plugins": [
        "@babel/plugin-transform-runtime",
        "@babel/plugin-transform-computed-properties",
        ["@babel/plugin-proposal-decorators", { "legacy": true }],
        "@babel/plugin-proposal-function-sent",
        "@babel/plugin-proposal-export-namespace-from",
        "@babel/plugin-proposal-numeric-separator",
        "@babel/plugin-proposal-throw-expressions"
    ]
}

webpack config

module.exports = {
    output: {
        filename: "js/main.[fullhash:8].js",
    },
    module: {
        rules: [
            {
                test: /.(js|jsx)$/,
                exclude: /node_modules/,
                use: "babel-loader",
            },
            {
                test: /.(png|jpg|jpeg|gif|ico|svg|eot|ttf|woff|woff2)$/,
                type: "asset",
                generator: {
                    filename: "assets/[name].[hash][ext]",
                },
                parser: {
                    dataUrlCondition: {
                        maxSize: 20 * 1024, // 20kb
                    },
                },
            },
            {
                test: /.(scss|sass|css)$/i,
                use: [
                    MiniCssExtractPlugin.loader,
                    "css-loader",
                    "postcss-loader",
                    "sass-loader",
                ],
            },
        ],
    },
    resolve: {
        extensions: [".js", ".jsx", ".json"],
    },
    plugins: [htmlPlugin, miniCssExtractPlugin],
    devServer: {
        historyApiFallback: {
            rewrites: [{ from: /^/$/, to: "/index.html" }],
        },
    },
};

Does someone have clue why after replacing hardcoded numbers with computed property names this problems happens? I know its the reason because if i revert this change and go back to hardcoded numbers application is working properly.

How can i validate a check box using JustValidate and PHP, JAVASCRIPT

<div class="job-types-container">
                                        <ul class="cboxtags">
                                            <?php
                                            $sql2 = "SELECT * FROM job_type";
                                            $resultJobtype = $mysqli->query($sql2);
                                            if ($resultJobtype) :
                                                while ($jobtype = $resultJobtype->fetch_assoc()) :
                                            ?>

                                                    <li class="cboxtags-list">
                                                        <div class="cboxtags-wrapper" id="jobtypes-validator">
                                                            <input class="cboxtype-input" id="cboxtype-<?= $jobtype['id_name']; ?>" type="checkbox" name="jobtypes[]">
                                                            <label class="cboxtype-label" for="cboxtype-<?= $jobtype['id_name']; ?>">
                                                                <span class="cboxlabel-span">
                                                                    <svg class="plus-icon" xmlns="http://www.w3.org/2000/svg" height="1em" viewBox="0 0 448 512"><!--! Font Awesome Free 6.4.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license (Commercial License) Copyright 2023 Fonticons, Inc. -->
                                                                        <path fill="currentColor" d="M256 80c0-17.7-14.3-32-32-32s-32 14.3-32 32V224H48c-17.7 0-32 14.3-32 32s14.3 32 32 32H192V432c0 17.7 14.3 32 32 32s32-14.3 32-32V288H400c17.7 0 32-14.3 32-32s-14.3-32-32-32H256V80z" />
                                                                    </svg>
                                                                    <svg class="check-icon" xmlns="http://www.w3.org/2000/svg" height="1em" viewBox="0 0 512 512">
                                                                        <path fill="currentColor" d="M155 396.9L23.3 265.2c-9.4-9.4-9.4-24.6 0-33.9l21.3-21.3c9.4-9.4 24.6-9.4 33.9 0L160 293l162.8-162.8c9.4-9.4 24.6-9.4 33.9 0l21.3 21.3c9.4 9.4 9.4 24.6 0 33.9L187 396.9c-9.4 9.4-24.6 9.4-33.9 0z"></path>
                                                                    </svg>
                                                                    <span><?= $jobtype['job_type_name']; ?></span>
                                                                </span>
                                                            </label>
                                                        </div>
                                                    </li>
                                            <?php
                                                endwhile;
                                            endif; ?>
                                        </ul>
                                    </div>

here is how i use justvalidate

try {
    validatePostForm
      .addField("#jobtitle", [
        {
          rule: "required",
        },
      ])
      .addField("#num-people", [
        {
          rule: "required",
        },
      ])
      .addField("#municipality", [
        {
          rule: "required",
        },
      ])
      .addField("#barangay", [
        {
          rule: "required",
        },
      ])
      .addField("#jobtypes-validator", [
        {
          rule: "required",
        },
      ]);
    console.log("Validation added successfully");
  } catch (error) {
    console.error("Validation error:", error);
  }

Error
Error

i want to validate the job types using justvalidate but when i try to use the format in their example it is not working i also try to ask in ChatGPT but still not working can anyone help me please

I want that the error will show when there is no selected check box and the error will show in the last element of the list

MUI 5’s AutoComplete doesn’t allow the selected tags to be read out by a screenreader

I have a fairly standard use of AutoComplete, it’s the same as the Fixed Options example. When I run NVDA and tab into it, it doesn’t read out the already selected tags (in the above case ‘Pulp fiction’ and ‘Incepton’).

I can add an id to the tags with renderTags and I’ve tried to add an aria-describedby to both with componentProps={{paper: {'aria-describedby':'id-of-tag1 id-of-tag2'}}} and/or via the renderInput but I haven’t got anything to even appear in the source, let alone read out the pre-selected tags.

What am I missing, or is this not possible?

Synchronization of 2 swipers in vue3

Vue 3, composition api, typescript.

In my project there are 2 galleries on swiper, one of which is in a modal window. They are in different components and synchronized. By clicking on the preview, I pass the index like this:

const openLightbox = (index: number) => {
  lightbox.value = true;
  slide.value = index;
};



<swiper
      :slides-per-view="1.5"
      @swiper="onSwiper"
    >
      <swiper-slide v-for="(item, index) in reals" :key="item.id" @click="openLightbox(index)">
        <RealsSlide :reals_data="item" />
      </swiper-slide>
    </swiper>
    <teleport to="body">
      <div class="reals-lightbox" v-show="lightbox">
        <div class="reals-lightbox__dialog">
          <button @click="closeLightbox">
            <svg width="14" height="14"><use xlink:href="#close" /></svg>
          </button>
          <RealsCarousel :reals="reals" :current-slide="slide" />
        </div>
      </div>
    </teleport>

In the gallery component in the modal window I get index like this:

const props = defineProps({   currentSlide: Number });
        
  const { currentSlide } = toRefs(props);
        
  watch(currentSlide, () => {   
    if (swiperRef.value !== null) {
       swiperRef.value.slideTo(props.currentSlide);   
    }});

And it works fine if you don’t swipe the gallery in the modal window. If you swipe the gallery in the modal window, close the modal window, and then click on the preview again, the last slide from the swipe is displayed, and not the one that corresponds to the index.

console.log shows that the index is passed correctly.

What can cause such a problem with synchronization?

Scroll child element when in viewport

Can someone help?

I have multiple sticky child elements, some of these has an high height (more than the viewport).
Each child has the following structure:

<section>
  <div class="content">
    <div class="child"></div>
    ... 20 more child ...
  </div>
</section>

with the following css:

section {
  min-height: 682px;
  position: sticky;
  top: 80px;
}
.content {
  height: 618px;
  overflow-y: scroll;
  display: flex;
  flex-direction: column;
  gap: 5px;
}
.child {
  height: 120px;
}

How can i achieve this scroll behaviour:

  1. first i scroll normally the body
  2. when i reach the section with high height i need to scroll the section until i touch the bottom
  3. when i reach the bottom of the section i need to scroll normally the body

I need to achieve this without manually scroll the section content but only scrolling the body scrollbar..

I already write the IntersectionObserver that observe the section with high height.

I think a simple solution is to change the “focus” of the scroll between parent and child when necessary but I don’t know what the best way to solve this is in js.

I already try to add a scroll event listener and then scroll the content of the section with section.scrollBy(0, event.deltaY);

But the event.deltaY doesnt exist in the type event: Event in ts…

PHP Ajax JSON result values to different divs

I would like to split the json result of my ajax call and push the values to different divs.

How have the JS part to look (without jquery) ?
E.g. how can i push the result of $var100 to the div “ajaxDivIdOne” and $var200 to the div “ajaxDivIdTwo” ?

index.php

function funcSelect(str) {
  if (str == "") {
    document.getElementById("ajaxDivIdOne").innerHTML = "";
    return;
  } else {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        document.getElementById("ajaxDivIdOne").innerHTML = this.responseText;
        //$json_result
      }
    };
    xmlhttp.open("POST", "jsondata.php?q=" + str, true);
    xmlhttp.send();
  }
};
<form>
  <select name="selectname" onchange="funcSelect(this.value)">
    <option value="">--Please choose a Station--</option>
    <option value="station1">Station1</option>
    <option value="station2">Station2</option>
  </select>
</form>

<div id="ajaxDivIdOne">Div-One</div>
<div id="ajaxDivIdTwo">Div-Two</div>

jsonData.php

<?php

    $q = $_GET['q'];

    
if ($q == "station1") {     
    $var100 = "100";
    $var200 = "200";    
};


if ($q == "station2") {         
    $var100 = "11111";
    $var200 = "22222";  
};

$data = '{      
    "Title100": "' . $var100 . '",
    "Title200": "' . $var200 . '"       
}';
$json_result = json_decode($data);
var_dump($json_result);
    

echo nl2br("n");
echo nl2br($var100 ."n");
echo nl2br($var200 ."n");
?>

Exception “if” so that the button is displayed only when the data is completed

I need help adding an “if” exception to my code so that the “button” is displayed on the page only when the data in “$customtab.description” is completed in the module. Not all items have this completed and the button is displayed everywhere, but I would like it to be displayed only when the data is completed.

<div id="custom-tab-{$customtab.id_tab|escape:'htmlall':'UTF-8'}" class="tab-pane fade in revealOnScroll animated fadeInUp">{$customtab.description nofilter}</div>
        {hook h='displayAfterProductThumbs' product=$product}
        <button onclick="iframetrailer()" id="buttoniframe">Fullscreen</button>
        </div>

I would like to ask for help in adding “if” in such a way that the “button” will not be displayed on item pages that do not have “$customtab.description” completed.

JavaScript string equality seems sporadically broken in Chrome, possibly related to Web Workers?

I have a function in my application that is (for a very small percentage of users, but for a few people every day) raising an error that seems impossible. It looks like, from the error the function raises, 'center' !== 'center'. Every occurrence of this error happens on Chrome, and the first occurrence was on October 16, 2023. Users run into this error once or twice, then it seems to resolve itself.

Here’s a simplified version of the function. There’s a lot of code stripped out, but the relevant control flow is almost exactly the same.

function createBaseGradient(gradient) {
    const start = gradient.start;
    
    // ...

    if (start === 'center') {
        // ...
        return '...'
    }

    // ...

    if (start === 'left') {
        // ...
    } else if (start === 'top') {
        // ...
    } else if (start === 'bottom') {
        // ...
    } else if (start === 'right') {
        // ...
    } else {
        internalError(
            `Illegal gradient start (${JSON.stringify(start)}, ${encodeURIComponent(
                start
            )}, ${stringToCharCodes(
                start
            )}) of type ${typeof start}. Webworker: ${isWebWorker}. Valid gradient starts are: (${VALID_STARTS}, ${VALID_STARTS.map(
                stringToCharCodes
            )})`
        );
    }

    // ...

    return '...';
}

Here is the exact text of one of the errors I’ve seen:

Error: Illegal gradient start (“center”, center, 99,101,110,116,101,114,END) of type string. Webworker: false. Valid gradient starts are: (center,left-top,left,left-bottom,top,bottom,right-top,right,right-bottom, 99,101,110,116,101,114,END,108,101,102,116,45,116,111,112,END,108,101,102,116,END,108,101,102,116,45,98,111,116,116,111,109,END,116,111,112,END,98,111,116,116,111,109,END,114,105,103,104,116,45,116,111,112,END,114,105,103,104,116,END,114,105,103,104,116,45,98,111,116,116,111,109,END)

So the constant start is a string, with value "center", and all of the characters of the string are the same characters as the characters in the string "center", in the same order. Yet start === 'center' can’t have been true, because we didn’t enter the first if statement and return.

A few more details that may be relevant: The argument gradient is created in a web worker before being used in this function. gradient.start is converted to a JavaScript string from a Brython string type. And this error does occur for other values of start.

Here’s what I’ve tried so far: I added the detailed logging that I included above. I tried storing all strings in the function in constants, and using those constants to create the VALID_STARTS array, just in case some browser extension was modifying the strings, but that doesn’t seem to be the case. I added more logging, not included above, to throw an error if we somehow entered the start === 'center' case and continued without returning, but that error has never triggered.

I also tried to create a minimal example of a possible Web Worker bug (where the string 'abc' posted from a Web Worker may not equal 'abc'). I ran it a few million times on my computer, but it never produced an error. The date of the first error doesn’t coincide with a new Chrome release or any relevant deploys on my end. I briefly skimmed the open bugs in Chrome, but it didn’t seem like I was going to have great luck there.

I’d really appreciate hearing new perspectives on how to tackle this bug, and insights from any JS gurus out there. Could this string not be a string, despite typeof start being 'string'? Could I be accidentally modifying the string prototype and breaking equality somehow? I’m not sure where to look next.

Thanks so much for any ideas you might have!

Cannot import a key generated using ssh-keygen

I am trying to import an ECDSA public key generated using the ssh-keygen command in order to verify signatures using the subtle crypto module. I am getting an error, but without any details.

The command I’m using to generate the key:

ssh-keygen -t ecdsa

And the public key looks like this:

ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBNBCvx3dHLrP0cXR0Iev5laJombKI7N4ND4wXdnwACrs5q2x1zIT9Adf9QtyVkc61acE1xzQ6sqnELAzw511cBM= 

Here’s a minimal snippet to reproduce the issue. It’s a file input that reads the public key as an ArrayBuffer and tries to load it using the importKey() method.

const loadKey = async (data) => {
    const key = await crypto.subtle.importKey(
        'raw',
        data,
        {
            name: 'ECDSA',
            namedCurve: 'P-256',
        },
        false,
        ['verify']
    )
    
    return key
}

const awaitedFR = async (file) => new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.addEventListener('load', ({target}) => resolve(target.result))
    reader.addEventListener('error', reject)
    reader.readAsArrayBuffer(file)
});

(async () => {
    const _main = document.querySelector('main')

    const fileInput = document.createElement('input')
    fileInput.type = 'file'
    fileInput.addEventListener('change', async ({target}) => {
        const file = target.files[0]
        const res = await awaitedFR(file)
        console.log(res)
        try {
            const key = await loadKey(res)
            _main.innerHTML += 'Succesfully loaded public key'
        } catch (error) {
            _main.innerHTML += 'Failed to load public key: ' + JSON.stringify(error)
        }
        console.log(key)
    })

    _main.appendChild(fileInput)
})();
<main></main>

Using the browser devtools I can see that the ArrayBuffer is correctly loaded in memory and the curve is properly set in the importKey() EcKeyImportParams.curve parameter (ssh-keygen defaults to NIST-P256).

I have no clue as of why this does not work, the script just fails silently. I also tried to export the key as PKCS#8 (and changing the format argument of the importKey() method) but to no avail.

There is no problem using keypairs generated directly in the browser though, my guess so far would be a formatting issue.

State increasing +40 instead of +20

I want to increase each item in sliderValues +20 when clicking Increase Volume.

import React, { useState, useRef } from 'react';

export const App = ({ name }) => {
  const [sliderValues, setSliderValues] = useState([50, 50, 50, 50, 50]); // Initial slider values

  const audios = [
    { src: '/fire.mp3', icon: '\f06d' },
    { src: '/crickets.mp3', icon: '\e4d0' },
  ];

  const increaseVolume = () => {
    audios.forEach((audioRef, index) => {
      setSliderValues((prevValues) =>
        prevValues.map((prevValue) => {
          console.log(prevValue); // Log the previous value
          return prevValue + 20;
        })
      );
    });
  };

  return (
    <div>
      <button onClick={increaseVolume}>Increase Volume</button>
      {/* Displaying the slider values */}
      <ul>
        {sliderValues.map((value, index) => (
          <li key={index}>{value}</li>
        ))}
      </ul>
    </div>
  );
};

But right now, the items are increasing by +40. I think it’s because there are two loops (forEach and map) and the +20 is being applied twice. But I’m not very sure how to fix this. Any suggestions?

Current output:

90
90
90
90
90

Desired output:

70
70
70
70
70

Working code on StackBlitz.

Tabulator Editor List doesnt select the label instead it select value and it doesnt preselect value using valuesLookup

I have a tabulator table, which i editable and i have one column with editor type is list. for that list iam fetching the data using valuesLookup inside using ajax i fetch the records. bind the data to list dropdown its working fine.

here is the working application link:

```https://jsfiddle.net/x7t2bg3v/```

Issue:

  • When i click on the cell which initially binded the data, then if i click esc or i click outside the cell then the preselected data gets clear and made it empty.
  • When i select an option from the list, it get select and in display it shows the value data, not the label. List Data is fetch from the ajax.
  • I have give the clearable true for clearing the selected option from the list, but its not showing the clear button.

Problem at building a ble scanner in Android Studio with cordova, using the Cordova-bluetoothle-plugin

At the moment i’m programming an application to config a gateway-device.
For this, i use android studio with cordova and the cordova-bluetoothle-plugin for JavaScript.

At first i would like to build a simple BLE-Scanner which searches for BLE-Devices and insert they in a table.

Every time i scan for devices, i get this error in the logcat of Android Studio:

2023-11-29 14:32:19.511  7022-7022  chromium                io.cordova.hellocordova              I  [INFO:CONSOLE(22)] "Uncaught ReferenceError: bluetoothle is not defined", source: https://localhost/js/index.js (22)

Here is my HTML:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" href="css/index.css">
    <title>GateWay-Configuration</title>
    <!--<script type="text/javascript" src="js/device.js"></script>-->
    <script type="text/javascript" src="js/index.js"></script>
    <script type="text/javascript" src="plugins/cordova-plugin-bluetoothle/www/bluetoothle.js"></script>
</head>
<body>
<!--<script>window.onload = scanForDevices;</script>-->
<div id="header">
    <text id="headline">GateWay-Configuration</text>
    <text id="secHeadline">Device-List</text>
</div>
<div id="content">
    <!--<text id="status">Not searching</text>
        <table id="DeviceTable">
        <tr>
            <td></td>
            <td></td>
        </tr>
    </table>-->
    <table border="1">
        <thead>
        <tr>
            <th>Number</th>
            <th>Name</th>
            <th>Address</th>
        </tr>
        </thead>
        <tbody id="deviceTableBody">
        <!-- Device entries will be added here -->
        </tbody>
    </table>
</div>
<button type="button" id="buttonAtBottom" onclick = "onDeviceReady()">Scan for Devices</button>
</body>
</html>

And here is my JS:

function onDeviceReady() {
    document.getElementById('deviceTableBody').innerHTML = '<tr><td colspan="3">Searching for devices...</td></tr>';
    findDevices();
}

function displayDevices(devices) {
    var tableBody = document.getElementById('deviceTableBody');
    tableBody.innerHTML = ''; // Clear existing entries

    if (devices.length > 0) {
        for (var i = 0; i < devices.length; i++) {
            var device = devices[i];
            var row = `<tr><td>${device.nr}</td><td>${device.name}</td><td>${device.address}</td></tr>`;
            tableBody.innerHTML += row;
        }
    } else {
        tableBody.innerHTML = '<tr><td colspan="3">No devices found</td></tr>';
    }
}

function findDevices() {
    bluetoothle.startScan({ services: [] }, function (result) {
        if (result.status === 'scanResult') {
            displayDevices(result.scanRecord);
        } else if (result.status === 'scanStarted') {
            // Scanning started
        } else if (result.status === 'scanStopped') {
            // Scanning stopped
        }
    }, function (error) {
        console.error("Error during Bluetooth scan: " + JSON.stringify(error));
    });

    setTimeout(stopScan, 5000); // Stop scanning after 5 seconds (adjust as needed)
}

function stopScan() {
    bluetoothle.stopScan(function (result) {
        // Scanning stopped
    }, function (error) {
        console.error("Error stopping Bluetooth scan: " + JSON.stringify(error));
    });
}

I already have tried to reinstall the plugin by using the comands:

$ cordova plugin rm cordova-plugin-bluetoothle
$ cordova plugin add cordova-plugin-bluetoothle

The plugins seems to be install successfully:

cordova plugin ls
cordova-plugin-bluetoothle 6.7.4 "Bluetooth LE"

And i have already tried to reinstall the plattform by using the commands:

$ cordova platform rm android
$ cordova platform add android

The error is still the same

Does someone has an idea how i can fix this error?