ID match with differen fields using if condtion in JS?

I Have two objects booking and History. I have to check booking userId matches with History userId or History CustomerID

If booking userId matches with any of these two fields(History userId or History CustomerID) we should return “ID matched” in the console.

If booking userId does not match with any of these two fields(History userId or History CustomerID). we should return “ID not matched with booking”.

Below is my code .its working as expected but is this a better approach? or i can do this in some other way

Please suggest

var booking = {"userId":"1233","CustomerID":null,"username":"av"};
var History = {"userId":"123","CustomerID":null,"username":"av"};

var a = booking.userId != History.userId;
var b = booking.userId == History.CustomerID;
var c = booking.userId == History.userId;
var d = booking.userId != History.CustomerID;
console.log(a)
console.log(b)
console.log(c)
console.log(d)

if( a && !b || c && !d)
{
console.log("ID not mathced with booking ")
}else{
console.log("ID mathced")
}

Uncaught ReferenceError: removeFiled is not defined

I am getting Function Reference undefined error while i add new Dynamic Fields. Note that I have split my bladed files into different parts or sections. but the function is defined in the same file. So basically i have a different- different part of files to make code easier to read. but the problem is when i write a function in a different file and mention that function name in the different file where all files part being included in one file. after that, i am getting errors many times like this `foo is not defined. in other words, all part of the files is included in one file. let’s check my code.

it is a script file in blade: script.blade.php

 <script> 
   var count_custom_field =0;
   $(document).on('click', '.new-row-weekly', function () {
    count_custom_field++;
    $(' <div class="clearfix field_'+count_custom_field+'" >&nbsp;</div>  ' +
        ' <div class="row field_'+count_custom_field+'">  <div class="col-md-4">  ' +
        ' <label class="text-label"> Repeat Day </label> {{ Form::select("repet_days[]",
         $days,null,array("class" => "form-control")) }} </div>  '+
        '  <div class="col-md-4">  ' +
        '  <label class="text-label"> Repeat Return Halt Duration(Minutes) </label>{!! Form::text("repet_times[]", null,
        array("class" => "form-control  repet_times" , "placeholder"=>"Ex. 120" ) ) !!} 
    </div>'+
        '  <div class="btn btn-danger"  onClick="removeCustFiled(213123)"  style="margin: 30px 0 0 0; height: 40px; padding-bottom: 18px;" > <i class="fa fa-close"></i> </div> </div> '+
        '</div>' ).appendTo('#weekly').hide().fadeIn(280);
   }

    function removeCustFiled( ref ) { console.log(ref);
       /* $('.'+ref+'').remove();
        if( Number( count_custom_field ) > 0)
        {
            count_custom_field--;
        }*/
    }
  </script>

UI blade file.
enter image description here

enter image description here

Please tell me what is reason i am getting this error.

Creating custom React hook to store File(s) (push/ purge), doesn’t render component where it is used

I’ve a create-react-app project with custom hook like this:

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
const useStagedUploads = () => {
    const [items, setItems] = useState<CustomFileWithPath[]>([]);
    const setUploadItems = (files: CustomFileWithPath[]) => setItems(files);

    return [items, setUploadItems] as const;
};

export default useStagedUploads;

I use it to push files to when browsed (using react-dropzone). Now in one of my other component, I use it like below *:

const [ items, setUploadItems ] = useStagedUploads();

    useEffect(() => {
        if (items) {
            onDrop(items);
            // eslint-disable-next-line @typescript-eslint/no-unsafe-return
            items.map((i) =>
                // eslint-disable-next-line @typescript-eslint/no-unsafe-return
                setUploadItems(
                    items.filter(
                        (items: CustomFileWithPath) => items.path !== i.path
                    )
                )
            );
        }
    }, [items]);

Now when upload is made like so (react-dropzone):

const { getInputProps, open, acceptedFiles } = useDropzone({
        noClick: true,
        noKeyboard: true,
    });

    useEffect(() => {
        if (acceptedFiles) {
            // eslint-disable-next-line @typescript-eslint/no-unsafe-return
            acceptedFiles.map((el) => stageUpload(el));
        }
    }, [acceptedFiles]);

… The former component (*) doesn’t re-render (tried console, debugger, etc.) ie I don’t receive items its empty “[]” array. Also doesn’t react useEffect body.

Gave a try using simple primitive type it does re-render. Is it so that files couldn’t be stored in react custom hooks or prevents re-render/ any serialization problem?

Thanks.

Publish app in Google play store when migrating from expo to bare react native

I had developed an app using Expo and published it in Google Play Store. It was running fine till now. But now I have a requirement to add a payment gateway. As of now, only stripe is available in expo. I wanted to add Razorpay Payment Gateway in the app.

So, I tried to eject the app and worked on it. But there were certain issues while building apk file. Then I tried to create a bare react native app from scratch and eventually I completed the work.

Now I want to publish the app in google app store.

If I create new keystore credential and upload it in Play store, will it work or I will have to use same keystore credentials that i used using expo.

Execute code without importing anything from .ts file [duplicate]

I have a file named listener.ts which has the following code.

import eventEmitter from './event';

eventEmitter.on('error', () => true); // TODO: Include calling of Bugsnag on callback.

I want to execute code of listener.ts file on starting up in main.ts file, without importing anything.

How can i achieve such functionality in Typescript ?.

Get API response properly

I am using:

https://api-v3.mbta.com/docs/swagger/index.html#/Schedule/ApiWeb_ScheduleController_index

and I am trying to create something like dashboard where you can see arriving and departing trains.
As far as I can see, if I use API route like this:

https://api-v3.mbta.com/schedules?filter[stop]=place-north

I am getting everything except name of the direction(where the train is heading to?). How I can add the name? I tried several stuff like this:

https://api-v3.mbta.com/schedules?filter[stop]=place-north&include=route.data.id.attributes

But unfortunately not getting the proper result.
My dashboard be something like this:

https://commons.m.wikimedia.org/wiki/File:North_Station_departure_board,_December_2011.jpg

(intermediate value).setTitle(…).setDescription(…).setThumbnail(…).addFields(…).setImage(…).setTimeStamp is not a function, Discord.js

Hi’ I’ve been trying to code an embed for my bot to send but I keep getting the same error “(intermediate value).setTitle(…).setDescription(…).setThumbnail(…).addFields(…).setImage(…).setTimeStamp is not a function”

I’ve looked online for answers but all people who had the same problem had errors in their code in areas mine doesn’t, I’ve been looking for hours and I have no idea what’s wrong. this is my code:

const { SlashCommandBuilder } = require('@discordjs/builders');
const { MessageEmbed, MessageAttachment} = require('discord.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('information')
        .setDescription('Returns info based on input')
        .addSubcommand(subcommand =>
            subcommand
                .setName("user")
                .setDescription("Gets information of a user mentioned")
                .addUserOption(option => option.setName("target").setDescription("The user mentioned")))
        .addSubcommand(subcommand =>
            subcommand
                .setName('server')
                .setDescription("Gets information about the server")),
    async execute(interaction, client) {
        if (interaction.options.getSubcommand() === "user") {
            const user = interaction.options.getUser("target");
            if (user) {
                const file = new MessageAttachment("./src/images/mayancoin.png");
                const userEmbed = new MessageEmbed()
                    .setTitle(`${user.username} Information:`)
                    .setDescription("test")
                    .setThumbnail(client.user.displayAvatarURL())
                    .addFields(
                        { name: `Username:`, value: `Username is: ${user.username}`, inline: true},
                        { name: `u200B`, value: `u200B`, inline: true },
                        { name: `Tag:`, value: `Tag is: #${user.discriminator}`, inline: true }
                    )
                    .setImage("attachment://mayancoin.png")
                    .setTimeStamp()
                    .setColor("#009988")
                    .setFooter(client.user.tag, client.user.displayAvatarURL());

                await interaction.reply({ embeds: [userEmbed], files: [file] });
            } else {
                await interaction.reply(`Username: ${interaction.user.username}nYour ID: ${interaction.user.id}`);
            }
        } else if (interaction.options.getSubcommand() === "server") {
            await interaction.reply(`Server Name: ${interaction.guild.name}nTotal Members: ${interaction.guild.memberCount}`);
        } else {
            await interaction.reply("No sub command was used");
        }
    },
};

Any help is appreciated

Testcafe AWS Cognito Login – Input not recognized as visible

I’m building a website and as a part a AWS Cognito login is used. I now wanted to write e2e test in TestCafe, but I’m struggling to get the Cognito login form to work with TestCafe.

When no session is found, the page will redirect you to the proper AWS Cognito OAuth “login” page.

The following test code will fail

import { Selector } from 'testcafe';

const config = {...};

test('Logging in', async t => {
    await t
        .typeText(Selector('input#signInFormUsername'), config.credentials.username)
        .typeText('input#signInFormPassword', config.credentials.password)
        .click('input[type=submit]');
});

with the error

The element that matches the specified selector is not visible.

...

       21 |});
         22 |
         23 |//then create a test and place your code there
         24 |test('Logging in', async t => {
         25 |    await t
       > 26 |        .typeText(Selector('input#signInFormUsername'), config.credentials.username)
         27 |        .typeText('input#signInFormPassword', config.credentials.password)
         28 |        .click('input[type=submit]');
         29 |});
         30 |

And in deed, when I execute the test

test('Logging in', async t => {
    const usernameInputVisible = usernameInputSelector.visible;
    await t.expect(usernameInputVisible).ok();
});

it does fail.

The curious thing is a) I do actually see the element and b) it’s neither display: none nor visibility: hidden as descripted here under visible.

The element does exists according to TestCafe as the following does not fail:

test('Logging in', async t => {
    const usernameInputExists = usernameInputSelector.exists;
    await t.expect(usernameInputExists).ok();
});

What am I missing here? How do I get TestCafe to work with the AWS Cognito OAuth login page?

Setup:

$ sw_vers
ProductName:    macOS
ProductVersion: 12.2.1
BuildVersion:   21D62

$ node --version    
v16.14.0

$ testcafe --version
1.18.4

Uploading files with Ajax and PHP but does not write data to database

I want to upload file and write the uploaded file name and upload time into database. In the code below, the file is loaded, but it does not write the data to the database. Why do you think it might? Is there anyone who can help with the issue? Where exactly could I be making the mistake?

Form Block Code

<form id="upload_form" enctype="multipart/form-data" method="post">
  <input type="file" name="file1" id="file1"><br>
  <input type="button" value="Gönder" onclick="uploadFile()">
  <progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
  <h3 id="status"></h3>
  <p id="loaded_n_total"></p>
</form>

Ajax Code

function _(el) {
  return document.getElementById(el);
}

function uploadFile() {
  var file = _("file1").files[0];
  // alert(file.name+" | "+file.size+" | "+file.type);
  var formdata = new FormData();
  formdata.append("file1", file);
  var ajax = new XMLHttpRequest();
  ajax.upload.addEventListener("progress", progressHandler, false);
  ajax.addEventListener("load", completeHandler, false);
  ajax.addEventListener("error", errorHandler, false);
  ajax.addEventListener("abort", abortHandler, false);
  ajax.open("POST", "upload_file_for_booking.php");
  ajax.send(formdata);
}

function progressHandler(event) {
  _("loaded_n_total").innerHTML = " Uploaded " + event.loaded + " bytes to " + event.total;
  var percent = (event.loaded / event.total) * 100;
  _("progressBar").value = Math.round(percent);
  _("status").innerHTML = Math.round(percent) + "% Uploaded ... Please Wait";
}

function completeHandler(event) {
  _("status").innerHTML = event.target.responseText;
  _("progressBar").value = 0;
}

function errorHandler(event) {
  _("status").innerHTML = "Upload Failed";
}

function abortHandler(event) {
  _("status").innerHTML = "Upload Aborted";
}

PHP Code

<?php 
$localhost = "localhost"; #localhost
$dbusername = "my_user_name"; #username of phpmyadmin
$dbpassword = "my_password";  #password of phpmyadmin
$dbname = "my_db_name";  #database name

$conn = mysqli_connect($localhost,$dbusername,$dbpassword,$dbname);

$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true


if (!$fileTmpLoc) { // if file not chosen
    echo "Hata : Please select file";
    exit();
}

if(move_uploaded_file($fileTmpLoc, "upload/$fileName")){
    $sql = "INSERT INTO `uploads` (`id`,`file_name`,`upload_time`) VALUES (NULL,'$fileName','2020-03-18 08:18')";
    echo "$fileName Upload Complete.";
} else {
    echo "Error";
}
?>

Modal is refresh on KeyPress

I know there are question asked before, but I have tried the solution but it’s not working. I have split the component differently but then also it refresh on every single keypress.

    const TenementRegistration = () => {

   const [show, setShow] = useState(false);
   const [name, setName] = useState("");
   const [editId, setEditId] = useState("");
    
    function Example() {

  

    const onSubmitHandler = async () => {
      
      const data = {
        name: name
    }
     await services.postService("User", data).then((res) => {
              onGetUserData();
            });
    }

    return(

          <Modal
          show={show}
          onHide={() => setShow(false)}
          size="lg"
          aria-labelledby="example-custom-modal-styling-title"
          scrollable="true"
          centered
          animation="true"
        >
          <Modal.Header closeButton>
            <Modal.Title id="example-custom-modal-styling-title">
              Add User
            </Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <div className="form-container">
              <form>
                <Row>
                  <div className="form-group col-12 col-md-6 center">
                    <label for="inputName" className="asy-FormLabel">
                      Name
                    </label>
                    <input
                      type="text"
                      className="form-control asy-InputValues"
                      id="policyName"
                      placeholder="Enter Property Id"
                      onChange={(e) => {
                        setName(e.target.value);
                      }}
                      value={Name}
                      required
                    />
                  </div>
</Row>
              </form>
</div>
</Modal.Body>
          <Modal.Footer>
            <button
              type="button"
              className="submit-button"
              onClick={() => 

    {
              
    
          onSubmitHandler();
                  }}
                >
                  Submit
            </button>
</Modal.Footer>
        </Modal>

    const [data, setData] = useState([]);

  useEffect(() => {
    onGetUserData();
  }, []);

  const onGetUserData = async () => {
    services.getService("User").then((res) => {
      setData(res.data);
    });
  };
const onEditData = async (id) => {
setShow(true);
 const newData = data.filter((obj) => obj.id === id)[0];
 setName(newData.name);
}
//Table where we show name and pass id to update button
}

I have also tried to Split the Modal and separate the form (not in this example) but it didn’t work any suggestions how to handle the modal problem

how to create a chart with a callback function for the x-axis if the values are numbers?

I try to create a line-chart with numbers for the x-axis (the ‘kw’ value), but it only works if the value is in string format. I use a callback function to add a string to the value in the legend. How can I create the chart with numbers from the data and add a string to it for the legend?
I hope you can see in my example what I mean.

With String:

var dString = [{
    kw: '1',
    wert: 120
  },
  {
    kw: '2',
    wert: 125
  },
  {
    kw: '3',
    wert: 110
  }
];

var dNumber = [{
    kw: 1,
    wert: 120
  },
  {
    kw: 2,
    wert: 125
  },
  {
    kw: 3,
    wert: 110
  }
];


dia(dString, 'dia');
dia(dNumber, 'dia2');


function dia(d, id) {
  var configDia = {
    data: {
      datasets: [{
        type: 'line',
        label: 'Ist',
        data: d,
        parsing: {
          xAxisKey: 'kw',
          yAxisKey: 'wert'
        }
      }]
    },
    options: {
      scales: {
        x: {
          ticks: {
            display: true,
            callback: function(value, index, ticks) {
              return `KW ${this.getLabelForValue(value)}`;
            }
          }
        },
        y: {
          ticks: {
            callback: function(value, index, ticks) {
              return value + '%';
            }
          }
        }
      }
    }
  };

  var ctx = document.getElementById(id);
  var myChart = new Chart(ctx, configDia);
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<canvas id="dia"></canvas>
<canvas id="dia2"></canvas>

Form check prevent from submiting even when everything is ok

i have a problem with my form, i ran it through the form checker and even when everything is successful it still won’t submit. i tried to change it a lot of times and im not sure how to keep the code like that instead of one function that will return on form submit.

const form = document.getElementById('form');
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');
const password2 = document.getElementById('password2');
const genderSelected = document.getElementById('select');
//Show input error messages
function showError(input, message) {
  const formControl = input.parentElement;
  formControl.className = 'form-control error';
  const small = formControl.querySelector('small');
  small.innerText = message;
}

//show success colour
function showSucces(input) {
  const formControl = input.parentElement;
  formControl.className = 'form-control success';
}

//check email is valid
function checkEmail(input) {
  const re = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
  if (re.test(input.value.trim())) {
    showSucces(input)
  } else {
    showError(input, 'Email is not invalid');
  }
}


//checkRequired fields
function checkRequired(inputArr) {
  inputArr.forEach(function(input) {
    if (input.value.trim() === '') {
      showError(input, `${getFieldName(input)} is required`)
    } else {
      showSucces(input);
    }
  });
}


//check input Length
function checkLength(input, min, max) {
  if (input.value.length < min) {
    showError(input, `${getFieldName(input)} must be at least ${min} characters`);
  } else if (input.value.length > max) {
    showError(input, `${getFieldName(input)} must be les than ${max} characters`);
  } else {
    showSucces(input);
  }
}

//get FieldName
function getFieldName(input) {
  return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}

// check passwords match
function checkPasswordMatch(input1, input2) {
  if (input1.value !== input2.value) {
    showError(input2, 'Passwords do not match');
  }
}

//check if selected a gender
function checkSelect(option) {
  if (select.value)
    showSucces(option);
  else
    showError(option, 'Please select a gender');
}



//Event Listeners
form.addEventListener('submit', function(e) {
  e.preventDefault();

  checkRequired([username, email, password, password2, genderSelected]);
  checkLength(username, 3, 15);
  checkLength(password, 6, 25);
  checkEmail(email);
  checkPasswordMatch(password, password2);
  checkSelect(genderSelected);
});
@import url('https://fonts.googleapis.com/css?family=Open+Sans&display=swap');
 :root {
  --succes-color: #2ecc71;
  --error-color: #e74c3c;
}

* {
  box-sizing: border-box;
}

.wrapper {
  width: 400px;
  max-width: 100%;
  box-sizing: border-box;
  padding: 25px;
  margin: 8% auto 0;
  position: relative;
}

.container {
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  width: 400px;
}

h2 {
  text-align: center;
  margin: 0 0 20px;
}

.form {
  padding: 30px 40px;
}

.form-control {
  margin-bottom: 10px;
  padding-bottom: 20px;
  position: relative;
}

.form-control label {
  color: #777;
  display: block;
  margin-bottom: 5px;
}

.form-control input {
  border: 2px solid #f0f0f0;
  border-radius: 4px;
  display: block;
  width: 100%;
  padding: 10px;
  font-size: 14px;
}

.form-control input:focus {
  outline: 0;
  border-color: #777;
}

.form-control.success input {
  border-color: var(--succes-color);
}

.form-control.error input {
  border-color: var(--error-color);
}

.form-control small {
  color: var(--error-color);
  position: absolute;
  bottom: 0;
  left: 0;
  visibility: hidden;
}

.form-control.error small {
  visibility: visible;
}

.form button {
  cursor: pointer;
  background-color: #3498db;
  border: 2px solid #3498db;
  border-radius: 4px;
  color: #fff;
  display: block;
  padding: 10px;
  font-size: 16px;
  margin-top: 20px;
  width: 100%;
}

form {
  border: 0px solid black;
  display: inline-block;
  text-align: left;
}

body {
  margin: 50px 0px;
  padding: 0px;
  text-align: center;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  margin: 0;
  background-color: lightblue;
}

.nav {
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
  display: inline;
  resize: horizontal
}

label,
input[type="text,password,date"] {
  display: block;
  width: 150px;
  float: left;
  margin-bottom: 10px;
}

input[type="radio"] {
  display: block;
  width: 25px;
  float: left;
  margin-bottom: 10px;
}

label {
  text-align: right;
  width: 75px;
  padding-right: 20px;
}

br {
  clear: left;
}

h1 {
  color: black;
  text-align: center;
  font-size: xx-large;
}

.button {
  text-align: center;
  margin: auto;
  display: inline-block;
  padding: 5px 15px;
  font-size: 18px;
  cursor: pointer;
  text-align: center;
  text-decoration: none;
  outline: none;
  color: black;
  background-color: white;
  border: none;
  border-radius: 15px;
  box-shadow: 0 9px #999;
}

.button:hover {
  background-color: black;
  color: white;
}

.button:active {
  background-color: black;
  color: white;
  box-shadow: 0 5px #666;
  transform: translateY(4px);
}

p {
  font-family: verdana;
  font-size: 20px;
}

#wrapper {
  width: 30%;
  margin: 50px auto;
  padding: 50px;
  background: #D7FBFF;
}

.textInput {
  border: none;
  height: 28px;
  margin: 2px;
  border: 1px solid #6B7363;
  font-size: 1.2em;
  padding: 5px;
  width: 95%;
}

.textInput:focus {
  outline: none;
}

.btn {
  width: 98.6%;
  border: none;
  margin-top: 5px;
  color: white;
  background-color: #3b5998;
  border-radius: 5px;
  padding: 12px;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  float: left;
  border-right: 1px solid #bbb;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover:not(.active) {
  background-color: #111;
}

.active {
  background-color: #04AA6D;
}

output {
  display: inline;
}

.customizedBox {
  border: 1px solid #111;
  width: 500px;
  height: 400px;
}

select {
  width: 280px;
  height: 40px;
  padding: 10px;
  margin: auto;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 1;
  border: none;
}
<div class="nav">
  <ul>
    <li><a href="HomePage.aspx">Home</a></li>
    <li><a href="MemesOverTheYears.aspx">Memes Over The Years</a></li>
    <li><a href="Profile.html">Profile</a></li>
    <li><a href="About.aspx">About</a></li>
  </ul>
</div>
<!-- partial:index.partial.html -->
<div class="wrapper">
  <div class="container">
    <form id="form" class="form">
      <h2>Register With Us</h2>
      <div class="form-control">
        <label for="username">Username</label>
        <input type="text" id="username" placeholder="Enter Username">
        <small>Error Message</small>
      </div>
      <div class="form-control">
        <label for="email">Email</label>
        <input type="text" id="email" placeholder="Enter email">
        <small>Error Message</small>
      </div>
      <div class="form-control">
        <label for="password">Password</label>
        <input type="password" id="password" placeholder="Enter password">
        <small>Error Message</small>
      </div>
      <div class="form-control">
        <label for="password2">Confirm Password</label>
        <input type="password" id="password2" placeholder="Enter password again">
        <small>Error Message</small>
      </div>
      <div class="form-control">
        <label for="gender">Gender</label> <br/>
        <select id="select">
          <option value="">Choose an option</option>
          <option value="Male">Male</option>
          <option value="female">Female</option>
          <option value="other">Other</option>
        </select>
        <small>Error Message</small>
      </div>
      <button type="submit">Submit</button>
    </form>
  </div>
</div>
<br /><br /><br /><br />
<span>Allready have an account?<a href="LogIn.aspx">Log In</a></span>

Can’t use chrome.runtime.getPackageDirectoryEntry in service work with the manifest v3 Chrome Extension standard

In manifest v2, I’ve used chrome.runtime.getPackageDirectoryEntry in the background script to list all the files within a subfolder that came with the extension to realize a specific design feature.

Now that Google is forcing me to migrate my extension from manifest v2 standard to manifest v3, I tried to do the same feature using the chrome.runtime.getPackageDirectoryEntry method but chrome would simply report this error:

Uncaught TypeError: chrome.runtime.getPackageDirectoryEntry is not a function

Can anyone help with this please?
or provide an alternative method for me to list all the filenames in a specified subfolder that would be shipped within the extension?

Find x-axis location to make an element move

I’m trying to make an element move backward on the X axis when the user presses “a”. However, I don’t know how to make it move farther every time the users presses that key :(. I’m new to JS

document.addEventListener("keypress", function (e) {
  let moveBy = 20;
  if (e.key === "a") {
    moveBy++;
    element.style.webkitTransform = `translateX(-${moveBy}px)`;
  }
}

Thank you!