How can I find a specific word and append an element in a Chrome extension?

I am greenhand in middle of making a chrome extension, which will search for specific text from the entire web , and then append a button element.

Actually, it’s a wordlist containing unfamiliar words, and I want to add a button near any of these unfamiliar words on each website.

I have implemented the manual word selection feature.

Like this: content-script.js

async function GetWordlist() {
    var { wordlist } = await chrome.storage.local.get(['wordlist'])
    wordlist = wordlist || []
    return wordlist
}


document.addEventListener('dblclick', async (event) => {
    var selection = window.getSelection()
    var selectedText = selection.toString().trim()
    if (selectedText.length > 0) {
        var wordlist = await GetWordlist()
        wordlist.push({
            content: selectedText,
            translation: `.... (Unfinish)`
        })
        await chrome.storage.local.set({wordlist})


        const range = selection.getRangeAt(0)
        console.log(range)

        const span = document.createElement('span');
        const button = document.createElement('button')
        {
            button.className = 'translated-word-btn'
            button.textContent = `$.... (Unfinish)`
            button.addEventListener('click', () => {
              //some features...eg.mark it familiar and delete this from the woldlist
            })
        }

            const originText = range.extractContents()
            span.appendChild(originText)
            span.appendChild(button)
            range.insertNode(span)
            const newRange = document.createRange()
            newRange.setStart(span, 0)
            newRange.setEnd(span, 1)

           //reselect the text
            window.getSelection().removeAllRanges()
            window.getSelection().addRange(newRange)
        

    }
});

When I select a word, I can append an element because I have the range of the selection, and I can easily add a new element. However, I don’t know how to search the entire page content. Help!

(I get innerText and search from it ,but cant locate the position of an element in the DOM)

TypeError: api.createContextKey is not a function when running Next.js development server

I am encountering an error while trying to run the development server for my Next.js project. Whenever I try to integrate MUI with my project I encounter these types of errors. The error message indicates a TypeError related to api.createContextKey not being a function. I have followed various troubleshooting steps, but the issue still persists. I’m seeking assistance to resolve this problem.

I would appreciate any guidance or insights on how to resolve this issue. Are there any additional steps I should take to troubleshoot? Is there a known compatibility issue with certain versions of Next.js or its dependencies? Thank you in advance for your assistance.

Steps taken:

Verified Node.js and npm versions:

Node.js: v16.17.0
npm: 8.15.0
Checked the project’s package.json file and confirmed the following relevant dependencies:

next: 13.4.10
react: 18.2.0
react-dom: 18.2.0
Troubleshooting steps already attempted:

  1. Deleted node_modules directory and reinstalled dependencies.
  2. Cleared npm cache using npm cache clean –force.
  3. Verified compatibility of Node.js version.
  4. Checked for conflicting global dependencies.
  5. Verified the correctness of package.json scripts:

The “dev” script is defined as “next dev”.
Output of npm list -g –depth=0 (global dependencies):

/Users/grace/.npm-global/lib
├── @microsoft/[email protected]
├── @pnp/[email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected]

Despite these efforts, the error persists when running npm run dev.

I have limited understanding with Next.js. I feel confident with regular React and it is very easy to use MUI components with just React. I understand because Next.js has defaulted server side rendered components we need to do some additional steps in set up. I follow tutorials step-by-step and still have issues running the project.

How do I make “10.0” return true while “10” return false

function validateResponse(number) {
    console.log(typeof(Math.round(number)))
    console.log(typeof(number))
    if ((isNaN(number)) || (Math.round(number) !== parseFloat(number)))
        return true;
    else
        return false
    //checks if number is integer and checks for decimal places
}

let input = require("readline-sync");


let num1 = input.question("t>>");
let num2 = input.question("t>>");
//lets say user inputs 10 for num1 and 10.0 for num2
console.log(validateResponse(num1));
console.log(validateResponse(num2));

I’m new to Javascript so my knowledge for it is limited. Correct me if I am wrong but does Javascript automatically convert “10.0” to a 10 if I did not use parseFloat?

Uppercases’ convention in JavaScript

From what i understand in JavaScript, the built-in objects that are avaible in the global scope start with the uppercase e.g: Math, Date, Array, Number and so on… So why is window written like this if it’s a global object too? Is there a specific reason?

I tryed to search on online js’documentations but i didn’t find anything

How to display data to the html tag in framework7

I am new in framework7 I want to pass value from an api to html, How am I going to achieve that in framework7, below is what I tried:

app.request
.get("http://127.0.0.1:8000/api/float-amount/" + phone_number, {
}).then(function (res) {
  var data = JSON.parse(res.data);
  var float_amount = data.float_amount;
  document.getElementById("float_amount").innerHTML = float_amount;
  console.log(float_amount);
});

Below is the html part where I want to display the value:

 <div class="item-title item-label" style="margin-top: 5%;" id="float_amount">Balance: 4000</div>

SyntaxError: await is only valid in async functions and the top level bodies of modules // Error: No tests found in Playwright

I am getting the following error: “SyntaxError: await is only valid in async functions and the top level bodies of modules // Error: No tests found” in Playwright. I am just starting to use Playwright. I changed the credentials and modified the code several times, but I keep getting the same error.

Here is the code:

import { Browser } from "playwright";

async function test() {
  // Create a new browser instance.
  const browser = await Browser.launch();

  // Open the login page.
  const page = await browser.newPage();
  await page.goto("https://guarnic-staging.web.app/signin");

  // Enter the email address.
  const emailInput = await page.locator("#basic_email");
  await emailInput.type("[email protected]");

  // Enter the password.
  const passwordInput = await page.locator("#basic_password");
  await passwordInput.type("temp4now");

  // Click the login button.
  const loginButton = await page.locator(".ant-btn ant-btn-primary gx-mb-0 submitButton--2D7G8");
  await loginButton.click();

  // Assert that the user is logged in.
  const logoutLink = await page.locator(".content--2i8zZ");
  if (!logoutLink) {
    throw new Error("User is not logged in");
  }
  await browser.close();
};

await test();

How to add value of input text next to checkbox value in list? And how to add onclick property to the input element

I’m trying to create a to-do list. I created a JavaScript code that appends the HTML tags in the list container. But how can I add the onclick property and text value of the input text next to the input checkbox?

<div id="to-do-list-container">
 <h3>To do List</h3>
 <ul id="list-items">
  <li>
   <div>
    <input type="checkbox" class="list-item-checkbox" onclick="Check_item()">Item 1</input>
   </div>
  </li>
  <li>
   <div>
    <input type="checkbox" class="list-item-checkbox" onclick="Check_item()">Item 2</input>
   </div>
  </li>
  <li>
   <div>
    <input type="checkbox" class="list-item-checkbox" onclick="Check_item()">Item 3</input>
   </div>
  </li>
 </ul>
 <form action="javascript:void(0);">
  <input type="text" id="list-item-input" placeholder="Enter item...">
  <input type="submit" value="ADD" onclick="Add_item()">
 </form>
</div>
function Add_item() {
 var listItem = document.createElement("li");
 var container = document.createElement("div");
 var checkbox = document.createElement("input");
 var itemName = document.getElementById("list-item-input");

 itemName.value = "";

 checkbox.type = "checkbox";
 checkbox.className = "list-item-checkbox";

 document.getElementById("list-items").appendChild(listItem);
 listItem.appendChild(container);
 container.appendChild(checkbox);
 checkbox.appendChild(itemName.value);
};

How to sort the array by specific requirements? [duplicate]

I have a table with names of devices like:

H4-22, X5-55, C6-11, C6-8, C6-12, CK3-43, CK3-45, CK3-46, …

I need to sort it so similar names will be near together.

My sorter looks like this atm:

    $(document).ready(function () {
            let table = $('#repairTable');
            let rows = table.find('tr:gt(0)').toArray().sort(comparer(0));
            for (var i = 0; i < rows.length; i++){ table.append(rows[i]) }

            function comparer(index) {
                return function(a, b) {
                    var valA = getCellValue(a, index), valB = getCellValue(b, index);
                    return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.toString().localeCompare(valB)
                }
            }
            
            function getCellValue(row, index) {
                return $(row)
                    .children('td')
                    .eq(index)
                    .text()
                    .split(' (')
                    .at(0)
                    .split(' ')
                    .at(-1)
            }
        });

The problem is it sorts C6-11, C6-8, C6-12 like C6-11, C6-12, C6-8 but I need to take into account that I also work with numbers. So in this case the result should be C6-8, C6-11, C6-12.

How can I handle numbers here?

My javascript event listener for a button is having a bug

I am trying to make a very basic RPG game where when you attack, the exp bar will decrease by 20px in css width.
Now that I have done it and everything seems to be working well, but then I noticed a bug when I clicked the attack button faster. The exp value is not decreasing by 20px at some point. It might just decrease by 10px or maybe even 3px. I am not sure if my math implementation is wrong or it’s a bug that I am yet to figure out.

Here is my javascript code :

const atkBtn = document.getElementById("atk-btn");
let expBar = document.getElementById("bar");

function attack(){
    var barWidth = expBar.offsetWidth;
    var atkVal = 20;
    newBar = (barWidth - atkVal)+"px";
    expBar.style.maxWidth = newBar;
    console.log(newBar)
}

atkBtn.addEventListener("click", attack);

Here is my css code :

p{
    margin: 0px;
    display: inline-block;
}

#bar{
    width: 200px;
    height: 15px;
    margin-top: 10px;
    background-color: red;
    display: inline-block;
    max-width: 200px;
    overflow-x: hidden;
    transition: all 0.4s;
}

Here is when I clicked the btn slowly:
enter image description here

Here is when I clicked the btn faster(to simulate gaming condition):
enter image description here

Should you have any answer please feel free to reply. Thanks

upload file to postgresql data base using react App

please #help all the data is added to the database except the file and there is no erreur

<inputtype="file"className="form-control"id="inputfile"aria-describedby="inputGroupFileAddon04"aria-label="Upload"//value={bonScanner}onChange={(e) => setBonScanner(e.target.files[0])}required/>

this is the function to insert the data

ProcessService.ajouterBon(
    fk_fournisseur,
    acheteur,
    bonScanner,
    type_bon,
    recepteur,
    livreur
  ).then((res) => {
    console.log(res.data);
    setId_bon(res.data[0].id_bon);
  });

i send data to the server

  const PRODUIT_API_BON = "http://localhost:8080/process/ajouterBon"; class ProcessService { ajouterBon(fk_fournisseur, acheteur, scanne_bon, type_bon, recepteur, livreur){

  const bon = { fk_fournisseur, acheteur, scanne_bon, type_bon, recepteur, livreur }
    
    return axios.post(PRODUIT_API_BON, bon)
}}

controller side

ajouterBon = (req, res) => {var datee = new Date();var heure = HeureNow();
var {scanne_bon} = req.files
var data = upload.dataconsole.log(data);

// Deconstruct x to get response values
res.send(“OK”)

const { fk_fournisseur, acheteur, scanne_bon, type_bon, recepteur, livreur } = req.body;pool.query(queries.ajouterReception,[fk_fournisseur, acheteur,scanne_bon, type_bon, datee, heure, recepteur, livreur],(error, result) => {if (error) throw error;res.status(200).json(result.rows);}, [data]);};

//in the qeury side

const ajouterReception ="INSERT INTO bon ( fk_fournisseur, acheteur,scanne_bon, type_bon, datee, heure, recepteur, livreur )VALUES ($1, $2, $3, $4, $5, $6, $7 , $8) RETURNING id_bon , recepteur , fk_fournisseur";

sorting data by value

I have array with objects

    const data = [
{
"bankNumber": 1,
"calculatedFee": 0,
"feeNumber": 4,
"group": "1",
},
{
"bankNumber": 1,
"calculatedFee": 147,
"feeNumber": 6,
"group": "1",
},
{
"bankNumber": 1,
"calculatedFee": 20,
"feeNumber": 10,
"group": "1",
},
{
"bankNumber": 2,
"calculatedFee": 10,
"feeNumber": 10,
"group": "3",
},
{
"bankNumber": 2,
"calculatedFee": 100,
"feeNumber": 10,
"group": "3",
},
{
"bankNumber": 3,
"calculatedFee": 100,
"feeNumber": 10,
"group": "2",
}
]

I would like to filter this data to get the smallest value calculatedFee with one group. For example calculatedFee = 0 is the smallest for the group 1, calculatedFee = 10 is the smallest for the group 3. However, I have no idea what function to create in javascript to get such results

How would I filter through data that was fetched by a server component? – NextJS 13 AppDir

I’ve been trying to figure out how to implement a search bar that filters through data that has been fetched by a server component using NextJS 13 and AppDir, but nothing has been working. I feel like I’m missing something though.

Most guides that explain search bar functionality tell you to use states, etc. However, this can only be used client side, not server side. I had implemented one of these, and tried to pass the value to the server side function, but no success.

I had the idea of using search params, but, these again can only be accessed by the client side. At this point I’m wondering what can server side functions even access?

I could put the fetch request on the client side and this would all probably work, but, correct me if I’m wrong, isn’t that incredibly unsecure? I have bearer tokens, etc, used for authentication that the client side would then be accessing.

Maybe I’m just missing the point (I probably am), but it would be greatly appreciated if someone could explain how implementing a search bar that filters through server-side fetched data would work.