Error occurs when usnig fetch in java script

When I attempt to use the fetch thing to use sdxl for a discord bout but it outprints an error

Heres my fetching function

async function query(data) {
    const response = await fetch(
        "https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-xl-base-1.0",
        {
            headers: {
                Authorization: "Bearer "+config.API,
                "Content-Type": "application/json"
            },
            method: "POST",
            body: JSON.stringify(data),
        }
    );
    const result = await response.json();
    return result;
}

.....
.....


const output = query(prompt)

And my error is


ExpectedConstraintError > s.string.url
  Invalid URL

  Expected: expected to match a URL

  Received:
  | '[object Promise]'

    at Object.run (D:Skye DataDownloadsmidjourney-bot-masternode_modules@sapphireshapeshiftdistcjsindex.cjs:2363:27)
    at D:Skye DataDownloadsmidjourney-bot-masternode_modules@sapphireshapeshiftdistcjsindex.cjs:939:67
    at Array.reduce (<anonymous>)
    at _StringValidator.parse (D:Skye DataDownloadsmidjourney-bot-masternode_modules@sapphireshapeshiftdistcjsindex.cjs:939:29)
    at ButtonBuilder.setURL (D:Skye DataDownloadsmidjourney-bot-masternode_modules@discordjsbuildersdistindex.js:651:34)
    at Object.run (D:Skye DataDownloadsmidjourney-bot-mastersrcslashCommandsinformationimagine.js:44:18)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Client.<anonymous> (D:Skye DataDownloadsmidjourney-bot-mastersrceventsclientinteractionCreate.js:43:9)

I was expecting it to change the reply into the image in which because of the error it just timed out.

Trigger Salesforce Marketing Cloud API Event on form submit

I am using Salesforce Marketing Cloud to send emails. I want to use the API Event in journey builder, I have tested the API using postman and the following code below and the journey is working fine, and the email is sending.

The issue I am facing is the following code triggers the API on page load and for a static subscriber. What I want to happen is to create a form so that when a user submits the SSJS will create a token and fire the API event.

I think this can be done with SSJS, but you cant mix SSJS and JS in the same script tag apparently.


%%[

SET @SubscriberKey = "0x00000001"
SET @EmailAddress = "[email protected]"
SET @PostalCode = "2000"

]%%

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]>      <html class="no-js"> <!--<![endif]-->
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="">
    </head>
    <body>
    <form id="myForm">
        <label for="name">Name:</label><br>
        <input type="text" id="name" name="name" required><br><br>
        <label for="email">Email:</label><br>
        <input type="email" id="email" name="email" required><br><br>
        <button type="submit">Submit</button>
    </form>
    </body>
    <script runat="server">

        Platform.Load("Core", "1.1.1");

        var data = {
            SubscriberKey: Variable.GetValue("@SubscriberKey"),
            EmailAddress: Variable.GetValue("@EmailAddress"),
            PostalCode: Variable.GetValue("@PostalCode")
        }

        var setup = {
            authBaseURI: "https://xxxxxxxxxxxxxxxxxxxx-xxxxxxx.auth.marketingcloudapis.com/",
            restBaseURI: "https://xxxxxxxxxxxxxxxxxxxx-xxxxxxx.rest.marketingcloudapis.com/",
            clientId: "xxxxxxxxxxxxxxxxxxxxxxxx",
            clientSecret: "xxxxxxxxxxxxxxxxxxxxxxxx",
            eventDefinitionKey: "APIEvent-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
        }

        try {
            var token = getToken(setup);
            var success = false;
            if (!!token) success = triggerEvent(token, setup, data);
            if (!!success) Write("Subscriber was successfully injected into the Journey");
            else Write("Failed to inject subscriber into the Journey");
        } catch (err) {
            Write("Error: " + Stringify(err));
        }

        function getToken(setup) {

            var config = {
                url: setup.authBaseURI + "v2/token",
                contentType: "application/json",
                payload: {
                    "client_id": setup.clientId,
                    "client_secret": setup.clientSecret,
                    "grant_type": "client_credentials"
                }
            }

            var req = HTTP.Post(config.url, config.contentType, Stringify(config.payload));

            if (req.StatusCode == 200) {
                var res = Platform.Function.ParseJSON(req.Response[0]);
                return res.access_token;
            } else {
                return false;
            }

        }

        function triggerEvent(token, setup, data) {

            var config = {
                url: setup.restBaseURI + "interaction/v1/events",
                contentType: "application/json",
                headerName: ["Authorization"],
                headerValue: ["Bearer " + token],
                payload: {
                    ContactKey: data.SubscriberKey,
                    EventDefinitionKey: setup.eventDefinitionKey,
                    Data: data
                }
            }

            var req = HTTP.Post(config.url, config.contentType, Stringify(config.payload), config.headerName, config.headerValue);

            if (req.StatusCode == 201) {
                var res = Platform.Function.ParseJSON(req["Response"][0]);
                if (res.eventInstanceId != null && res.eventInstanceId != "") return true;
            } else {
                return false;
            }

        }

    </script>
</html>

Lidar technology in object recognition

I have an idea to use lidar on the iPhone to be able to identify objects. Does anyone have any ideas to help me? I am building using java spring boot. Thank you!

I’m thinking, is it possible to export the iphone lidar scan file for comparison?

scraping with nodejs and cheerio

how to create a webscraper tool for static sites with node js ? i have used cheerio but its only scraping the homepage but how to scrap all the pages of a website or if i want any specific page

import axios from “axios”;
import * as cheerio from ‘cheerio’;

async function dataAfterScrapingWebs(url) {

try {
    const response = await axios.get(url);
    const $ = cheerio.load(response.data);
    const bodyText = $('body').text();
    const emailRegex = /([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+.[a-zA-Z0-9._-]+)/gi;
    const emails = new Set(); // Using a set to avoid duplicates;


    let match;
    while (match = emailRegex.exec(bodyText)) {
        emails.add(match[0]);
    }

    console.log(Array.from(emails), url);
    console.log(`Data scraped successfully from ${url}`);
    return { emails: Array.from(emails), websiteName: url }

} catch (error) {

    if (error.response) {

        console.error(`Error fetching data from ${url}. Status code: ${error.response.status}`);
    } else if (error.request) {

        console.error(`Error fetching data from ${url}. No response received.`);
    } else {

        console.error(`Error fetching data from ${url}:`, error.message);
    }
}

}

export default dataAfterScrapingWebs;

and its working its only scraping the first homepage but not able to build the logic how to get all the pages of a site

Unable to find audio files in Next.js

I am currently having issues importing my audio files into a redux slice.

Currently I am trying to get my audio files from the
app > public > audio directory.

I have tried to get my audio files via 2 different directories. But this still did not work..

const pomodoroErrorAlert = “/audio/pomodoroSuccessAlert.wav”;
const pomodoroSuccessAlert = “../../public/audio/pomodoroErrorAlert.wav”;

This is the error I got in return..

:3001/public/audio/pomodoroErrorAlert.wav:1

GET http://localhost:3001/public/audio/pomodoroErrorAlert.wav net::ERR_ABORTED 404 (Not Found)
localhost/:1 Uncaught (in promise) DOMException: Failed to load because no supported source was found.

Cannot connect to peerjs server in production nginx webserver

I am trying to set up a custom peerjs server but I can’t connect in production. I am using nginx on ubuntu server. I get the following error:

490.1fe86540fec474fb.js:12 WebSocket connection to 'wss://ps.mydomain.com/peerjs?key=peerjs&id=648463cc-0253-4472-9909-f57736…OjE3MTUzNjEzODZ9.KS9C_klV3zbDq1kbhzYFPyP_lvvUOXoy7bBcVmNvOXU&version=1.5.2' failed: WebSocket is closed before the connection is established.
490.1fe86540fec474fb.js:12 WebSocket connection to 'wss://ps.mydomain.com/peerjs?key=peerjs&id=1bbe4517-81bb-43fd-b42b-5f58ef…OjE3MTUzNjEzODZ9.dhCur0nOiUOaDJXXb7BIUk6yXiA1ZfwN7wbGZK_rN2w&version=1.5.2' failed: 

Here is how I am connecting in the client:

this.peer = new Peer(this.manager.user.uuid, {
  token: accessToken,
  host: 'ps.mydomain.com',
  port: 443
})

Here is peerServer.mjs

import 'dotenv/config'
import { PeerServer } from 'peer'
import { jwtVerify } from 'jose'

const serverConfig = {
  port: Number(process.env.PEER_PORT || 3001),
  path: '/peerjs',
  host: 'localhost',
  allow_discovery: true,
}

async function verifyToken(token) {
  const secret = new TextEncoder().encode(process.env.JWT_SECRET)

  if (!token) return null
  try {
    const { payload } = await jwtVerify(token, secret)
    return payload
  } catch (err) {
    throw err
  }
}

const peerServer = PeerServer(serverConfig)

peerServer.on('connection', async (client) => {
  try {
    const verified = await verifyToken(client.getToken())

    if (!verified?.uuid || verified?.uuid !== client.getId()) {
      client?.getSocket()?.close()
    }
  } catch (err) {
    client?.getSocket()?.close()
  }
})

peerServer.on('error', (err) => {
  console.error(err)
})

Here is my nginx config:

map $http_upgrade $connection_upgrade {
        default upgrade;
        '' close;
}

server {
    server_name ps.mydomain.com;

    location / {
        # WebSocket support
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Host $host;

        proxy_set_header Accept-Encoding "";
        proxy_pass http://localhost:5005;

        proxy_cache_bypass $http_upgrade;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_redirect off;
    }

    listen [::]:443 ssl; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
    if ($host = ps.mydomain.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80;
    listen [::]:80;

    server_name ps.mydomain.com;
    return 404; # managed by Certbot
}

Everything seems to be working fine. If I go to ps.mydomain.com/peerjs the peer server is running. I get the following output.

{"name":"PeerJS Server","description":"A server side element to broker connections between PeerJS clients.","website":"https://peerjs.com/"}

Not really sure what the deal is.I’ve tried adding proxied: true but that doesn’t work. I’ve also tried adding ssl certs to the serverConfig but then I get a bad request in the browser for ps.mydomain.com. I have also tried changing the location in nginx to location /peerjs but that doesn’t work either.

At this point I am out of ideas. Can someone please help.

Thanks.

I don’t understand this example for a callback function, in which we callback a function which hasn’t actually been declared

In the below example from Codecademy, I don’t really understand how the console can process the ‘artist’ parameter in a higher-order function, considering that we’ve only declared ‘artists’ up to this point?

const artists = ['Picasso', 'Kahlo', 'Matisse', 'Utamaro'];

artists.forEach(artist => {
  console.log(artist + ' is one of my favorite artists.');
});

How can we use ‘artist’ and not something like:

artist[i]

Page reload by it self after modal appears

I’m having an issue which is my page gets reload by itself after importing CSV file using the code below (the modal appears for seconds then page gets reloaded)

function handleFileUpload(event) {
    event.preventDefault();
    const fileInput = document.getElementById('fileInput');
    const file = fileInput.files[0];
    if (!file) {
        alert("No file selected. Please select a file.");
        return;
    }

    fileInput.disabled = true;  // Disable the file input while processing
    const formData = new FormData();
    formData.append('csvfile', file);

    fetch('http://localhost:3000/api/import/products', {
        method: 'POST',
        body: formData
    })
        .then(response => response.json())
        .then(result => {
            fileInput.disabled = false;  // Re-enable the file input
            displayResultsInModal(result);
        })
        .catch(error => {
            fileInput.disabled = false;
            console.error('Error:', error);
            alert(`Failed to upload file: ${error.message}`);
        });
}

function displayResultsInModal(result) {
    const modalBody = document.querySelector('#importResultModal .modal-body');
    modalBody.innerHTML = ''; // Clear previous contents

    if (result.error) {
        modalBody.textContent = result.error;
    } else {
        const content = document.createElement('div');
        content.innerHTML = `<p>Successfully imported ${result.data.length} items.</p>`;
        modalBody.appendChild(content);
    }

    $('#importResultModal').modal('show'); // Using jQuery to show the Bootstrap modal
}

And here is the HTML button part along with the modal

<button type="button"
class="btn btn-primary btn-label waves-effect waves-light mr-2"
                                            onclick="document.getElementById('fileInput').click();">
<i class="ri-file-add-fill label-icon"></i> Import CSV
</button>

<input type="file" id="fileInput" style="display: none;" accept=".csv"
onchange="handleFileUpload(event)">

Here is the Modal HTML

<!-- Import Results Modal -->
<div class="modal fade" id="importResultModal" tabindex="-1"
    aria-labelledby="importResultModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="importResultModalLabel">Import Results</h5>
                <button type="button" class="close" data-dismiss="modal"
                    aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <!-- Content will be filled dynamically by JavaScript -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary"
                    data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

The process works perfectly but the modal appears only for few second then the page reloads.

Any support? where i don’t want the page to be reloaded until i click confirm in the modal.

tried to use
event.preventDefault();
and nothing changed

i change the button type to button, and same issue.

How can I validate a radio input with JavaScript?

I have a problem:
I want to validate a input type="radio" with vanilla JavaScript (probably using document.getElementById), based on ECMAScript. How do I do it? Here is my HTML:

                    <div class="gender-input">
                        <input type="radio" name="gender" id="male">
                        <label for="male">Male</label>
                    </div>

                    <div class="gender-input">
                        <input type="radio" name="gender" id="female">
                        <label for="others">Female</label>
                    </div>
                

I don´t know how to creat a function to verify if the radio button is checked or not. I saw some posts talking about this, but all of them used some frameworks or another solutions, but I just want to use Vanilla JavaScript.

How to globally disable webpack prefetch magic comment

I have few modules lazy loaded and prefetched using the magic comment: /* webpackChunkName: “”*, WebpackPrefetch:true”

but I want to disable/enable webpack prefetch based on webpack config, as I have different build scenarios, and some of them shouldn’t have prefetch logic (i.e. adding the resource hint ).

I tried using LimitChunkCountPlugin but it doesn’t solve the problem.

Base64 Not encoding/decoding correctly

I have a website called [Pastebin}(https://paste-bin.us), that is a minimalistic version of the original Pastebin, but I am having trouble pasting code. My server won’t accept it.

I tried encoding it in base64 which worked, and stored the data as base 64, and when I went to decode it through a tool it decoded perfectly, but when I view it at the generated pastebin link it displays like �������Y� ��T��T��ԑTUQT and I can’t figure it out. I has a mostly working version that encoded and decoded perfectly but it wasn’t just displaying the code, but displaying it with the html in it. So if I had <h1>Test</h1> in my code, it would display it as a header and not the plain code. I tried to find this again but it got lose in my revisions. Below I have my current (not working) code that has base64 encoding/decoding/displaying errors, I cant figure out which.

JS

    window.onload = function() {
        document.querySelector('#pasteForm').addEventListener('submit', function(e) {
            e.preventDefault();
            var textArea = document.querySelector('#textToPaste');
            var formData = new FormData(e.target);

            var text = formData.get('text').replace(/n/g, '<br>').replace(/^ /gm, '&nbsp;').replace(/^t/gm, '&emsp;');
            var encodedText = btoa(text); // Encode the text in base64
            formData.set('text', '<pre>' + encodedText + '</pre>'); // Use the encoded text

            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'create.php', true);

            xhr.onload = function() {
                if (xhr.status === 200) {
                    var password = formData.get('password');
                    if (password) {
                        document.querySelector('#linkBox').value = xhr.responseURL + '?password=' + encodeURIComponent(password);
                    } else {
                        document.querySelector('#linkBox').value = xhr.responseURL;
                    }
                    document.querySelector('#overlay').style.display = 'block';
                    document.querySelector('#popup').style.display = 'block';
                } else {
                    console.error('An error occurred');
                }
            };

            xhr.send(formData);
        });

        document.querySelector('#closeButton').addEventListener('click', function() {
            document.querySelector('#overlay').style.display = 'none';
            document.querySelector('#popup').style.display = 'none';
        });

        document.querySelector('#copyButton').addEventListener('click', function() {
            var linkBox = document.querySelector('#linkBox');
            linkBox.select();
            document.execCommand('copy');

            var copyButtonIcon = document.querySelector('#copyButton img');
            var originalIconSrc = copyButtonIcon.src;
            copyButtonIcon.src = 'https://cdn.cirrus.center/main/icons/check.png';

            setTimeout(function() {
                copyButtonIcon.src = originalIconSrc;
            }, 2000);
        });
    };

PHP

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!file_exists('paste')) {
        mkdir('paste');

        $redirectIndex = '<?php' . PHP_EOL;
        $redirectIndex .= 'header("Location: ..");' . PHP_EOL;
        $redirectIndex .= 'exit;' . PHP_EOL;
        file_put_contents('paste/index.php', $redirectIndex);
    }

    $dir = uniqid();
    mkdir("paste/$dir");

    $decodedText = '';
    if (isset($_POST['text']) && $_POST['text'] !== '') {
        $decodedText = base64_decode($_POST['text']); // Decode the base64 text
        $decodedText = mb_convert_encoding($decodedText, 'UTF-8', 'auto'); // Convert the encoding to UTF-8
    }

    $index = '<?php' . PHP_EOL;

    if (isset($_POST['password']) && $_POST['password'] !== '') {
        $index .= 'if (!isset($_GET["password"]) || $_GET["password"] !== "' . $_POST['password'] . '") {' . PHP_EOL;
        $index .= '    echo "<h1>Incorrect password</h1>";' . PHP_EOL;
        $index .= '    exit;' . PHP_EOL;
        $index .= '}' . PHP_EOL;
    }

    $index .= 'echo <<<EOT' . PHP_EOL; // Use the decoded text
    $index .= $decodedText . PHP_EOL;
    $index .= 'EOT;' . PHP_EOL;

    if (isset($_POST['burn'])) {
        $index .= 'file_put_contents(__FILE__, "<h1>This paste has been deleted</h1>");' . PHP_EOL;
        $index .= 'exit;' . PHP_EOL;
    }

    $index .= '?>' . PHP_EOL;

    $index .= '<!DOCTYPE html>' . PHP_EOL;
    $index .= '<html>' . PHP_EOL;
    $index .= '<head>' . PHP_EOL;
    $index .= '    <title>' . ($_POST['title'] ?? 'Pastebin') . '</title>' . PHP_EOL;
    $index .= '</head>' . PHP_EOL;
    $index .= '<body>' . PHP_EOL;
    $index .= '' . PHP_EOL;
    $index .= '</body>' . PHP_EOL;
    $index .= '</html>';

    file_put_contents("paste/$dir/index.php", $index);

    header("Location: /paste/$dir");
    echo "/paste/$dir";
}

Multi-page form validation issue with react-hook-form and arrays

I have a multi-page react-hook-form form and I’m running into a validation issue I can’t seem to wrap my head around. I’m trying to only validate the page the user is on, not pages they haven’t made it to yet.

Here’s a CodeSandbox

If you enter something into the input and click “Next”, you can move on to the next page. If you click “Back” and then try to click “Next” again, it won’t let you because it’s validating the second page but the user isn’t on that page.

I should be able to freely go between page 1 and 2 even though I haven’t added an item to my field array. It should only validate if I try to click “Next” on the 2nd page.

JavaScript betting bot

Hi I have been diving into the world of coding for casino games online, but I am having issues achieving what I want and I need help in order to correct this, I would really appreciate the help of this community.

I want to write a script that bets at an initial amount 100 and at a odd say 1.18

that is initial bet will be 100 × 1.18 = 1,180

Then the next bet will be with the precious won amount that is 1180 × 1.18 = 1,392

And so on, this bet will run just for 4 times. Now the added functionality apart from this, is that I want the bot to wait for 5 minutes before executing the code for the next bet, that is the script runs for bet 1 ( 100 × 1.18 = 1,180) waits for 5 minutes and runs bet 2. It does this too till it runs for the 4th and final time and it stops running, after running for the 4th and final time it will wait for 1 hour and runs the script again.
below is the code I have written so far, it runs for 4 times but doesn’t wait for 5 minutes and neither does it use the previous won amount.

var config = {
    baseBet: {
        value: 100,
        type: 'number',
        label: 'Base Bet'
    },
    maxSteps: {
        value: 4,
        type: 'number',
        label: 'Max Fibonacci Steps'
    },
    payout: {
        value: 1.18,
        type: 'number',
        label: 'Payout'
    }
};

function main() {
    let currentStep = 0;
    let betCounter = 0;
    let previousBetAmount = config.baseBet.value;

    function placeBet() {
        let betAmount = previousBetAmount;
        betAmount = Math.max(betAmount, currency.minAmount);

        if (betAmount > currency.maxAmount) {
            log.error('Bet amount is too high. Maximum is ' + currency.maxAmount);
            game.stop();
            return;
        }

        if (betAmount > currency.amount) {
            log.error('Insufficient balance to place the bet.');
            game.stop();
            return;
        }

        game.bet(betAmount, config.payout.value).then(payout => {
            if (payout > 0) {
                log.success('Won! Payout: ' + payout);
                previousBetAmount = payout;
            } else {
                log.info('Lost. Moving to the next step in Fibonacci sequence.');
            }

            betCounter++;

            if (betCounter < config.maxSteps.value) {
                setTimeout(placeBet, 5 * 60 * 1000); // 5 minutes interval before the next bet
            } else {
                log.info('Finished ' + config.maxSteps.value + ' rounds of betting.');
                game.stop();
            }
        });
    }

    game.on('GAME_STARTING', function() {
        log.info('Game is starting. Betting ' + previousBetAmount);
        placeBet();
    });

    game.on('GAME_ENDED', function() {
        log.info('Game ended.');
    });
}

Thanks s much, as I await your help

I tried coding the bot to bet for 4 times but waiting for 5 minutes intervals between all for bets, but it’s not doing that

callback data from sendMessage is true

I have a script that should get a value from the backgroud, basically it returns an item, but also for some reason it returns true when the function is called again.

market.js

async function renderMarketItem(item) {
//parsers name, type and quality of item
let market_item = await new Promise((resolve, reject) => {
          if(chrome.runtime?.id) {
            chrome.runtime.sendMessage({ action: "getMarketItem", name: formatData(type, name, quality) }, (item) => {
              resolve(item);
            })
          }
          else resolve(undefined);
        });
//another logic
}


chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
      if (message.action == 'updateConfig') {
        $('.items-grid').children().each(function() {
          renderMarketItem($(this));
        })
      }
});


/*for example*/
$('.items-grid').children().each(function() {
          renderMarketItem($(this));
})


background.js

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
   if (message.action == 'getMarketItem') {
        sendResponse(getMarketItem(message));
    }
});

const getMarketItem = (message) => {
    
    let targetName = message.name;
    let item = [];
    if (targetName) item = items.find(item => item.market_hash_name.trim() == targetName.trim());
    return item;
}

I did function async with return true and it didn’t work