How to implement Tap To Focus for camera in JavaScript?

I’m working on a web application that has a custom camera screen, for which I’m supposed to implement tap to focus using getUserMedia

Here’s the code:

 const permissionConstraints = {
       video: { 
       width: { exact: 1280 }, height: { exact: 1280 },
       aspectRatio: { ideal: 1 }, facingMode: 'environment' }
 };

 navigator.mediaDevices.getUserMedia(permissionConstraints).then((permissionsObj) => {
        console.log(permissionsObj);
 })

how to use length-limit on RegExp Object with JavaScript?

const ipv6="([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+)";
const regex = new RegExp(ipv6);
const result = SAMPLE_STRING.match(regex);
console.log(result);

run code result is

SyntaxError: Invalid regular expression: /([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+):([a-zA-Z0-9]{1,4}+)/: Nothing to repeat

The ‘ipv6’ works with a regex-compiler, but not with javascript.

And i must use the ‘new Regex’ object.
how can i make the work?

How to wait for an object to be asynchronously edited?

I have an array of items where I want to append an async value getProductMinQuantity.

The problem is that the render res.status(200)... is sent before item.order_quantity_minimum had been edited.

I thought that a map like below would create a new promise with the items updated.

newResult is a type Promise<any>[] | undefined, I cannot do .then .catch to then execut my res.status in it.

const getCart = async () => {
  
  ...

  let newResult = result.data?.line_items.physical_items.map(async (item: any) =>
    item.order_quantity_minimum = await getProductMinQuantity(item.product_id)
  )

  res.status(200).json({
    data: result.data ? normalizeCart(result.data) : null,
  })
}

Any thought how I can arrange that ?

Why is event.target.files[0].name showing error in my code?

I have this JS code (given below) which converts a JSON file to XML file. Everything works perfectly (I get the contents of the file), but now I want to fetch the filename of the uploaded file.

function onChange(event) {
        var reader = new FileReader();
        reader.onload = (event)=>{
          let data = JSON.parse(event.target.result);
          $("#jsonArea").val(event.target.result);
          var finalXML = '<root>' + x2js.json2xml_str($.parseJSON(event.target.result)) + '</root>';
          var finalName = event.target.files[0].name; //setting it here
          $("#xmlArea").val(finalXML);

          finalXML = finalXML.split('FORM3CA').join('FORM3CB');
          finalXML = finalXML.split('F3CA').join('F3CB');
          finalXML = finalXML.split('<CreationInfo>')[0] + '<CreationInfo><SWVersionNo>1.0</SWVersionNo><SWCreatedBy>SW20000</SWCreatedBy><JSONCreatedBy>SW20000</JSONCreatedBy><JSONCreationDate>2021-11-21</JSONCreationDate><IntermediaryCity>311</IntermediaryCity></CreationInfo>' + finalXML.split('</CreationInfo>')[1]
          finalXML = finalXML.split('I_We1').join('I_We');
          
          console.log(finalName); //here
        }
        reader.readAsText(event.target.files[0]);
    }
 
document.getElementById('file').addEventListener('change', onChange);

I was suggested to use event.target.files[0].name in order to get the filename of the uploaded file (by @HeryKurniawan in comments of this post). But, when I try to console.log()the finalName variable (as you can see in above code), it shows me this error –

enter image description here

What is wrong in my code? I have also tried using event.target.file.name & event.target.file[0].name, but that doesn’t work either. Kindly guide… Thanks! 🙂

How can I set default checked in Ag-Grid React.js?

I use react ag-grid and I have checkboxSelection on row. I want to default checked some rows, not checked some rows. How can I do that ?

columnDefinationVoucherList: [
                { headerName: "", cellRenderer: countCellIndex, width: 50, minWidth: 40, maxWidth: 50, editable: false, },
                { headerName: "Belge Kodu", field: "ApplicationVoucher.Voucher.VoucherCode", width: 50, minWidth: 50, maxWidth: 80, suppressSizeToFit: true, sortable: true },
                { headerName: "Belge Adı", field: "ApplicationVoucher.Voucher.VoucherName", width: 120, minWidth: 50, suppressSizeToFit: true },
                { headerName: "Seç", field: "", width: 90, minWidth: 10, suppressSizeToFit: true, maxWidth: 50, checkboxSelection: true, },
            ],

                                          <AgGridReact
                                            columnDefs={this.state.columnDefinationVoucherList}
                                            headerHeight={30}
                                            rowHeight={20}
                                            rowData={this.state.documentList}
                                            onColumnResized={true}
                                            enableCellChangeFlash={true}
                                            enableCellTextSelection={true}
                                            enableCellExpressions={true}
                                            enableSorting={true}
                                            enableFilter={true}
                                            enableGroupEdit={true}
                                            enableRangeHandle={true}
                                            defaultColDef={this.state.shortGridDefaultColDef}
                                            rowSelection={'multiple'}
                                            onSelectionChanged={this.GetSelectedVouchers}
                                        >
                                        </AgGridReact>

Also I use enterprise mode. So I am open every solutions.

When Focus done on input field, fields remove the data

I am trying to input data using this function. this function is fetching data and doing formfilling but when the form focus on the input field or I try to submit from all, data disappears from all the fields and all input fields become red.

 if (Data[key].formname) {   
          $("[formcontrolname='"+Data[key].formname+"']").focus(); 
          $("[formcontrolname='"+Data[key].formname+"']").val(Data[key].value);
                        
                        await wait (1000)                        
                    }

specific item from an object in local storage is not removing

let cartItems = localStorage.getItem("ProductsinCart");
cartItems = JSON.parse(cartItems);
Object.values(cartItems).map(item => {

    let productNumbers2 = localStorage.getItem('cartNumbers2');
    productNumbers2 = parseInt(productNumbers2);
    let cartcost = localStorage.getItem('totalCost');
    cartcost = parseFloat(cartcost);
    let inCart = item.inCart;
    if (item.id === id)
    {

        localStorage.removeItem(cartItems[item.tag]);
        console.log(cartItems);
   
    }

CodingAllInOne:
description: “notNow”
id: 4
imgSrc: “./imagesForCart/programmingBooks/CodingAllInOne.jfif”
inCart: 1
inStock: 39
name: “Coding All In One”
price: 29.99
tag: “CodingAllInOne”
[[Prototype]]: Object
DesignPatterns:
description: “notNow”
id: 6
imgSrc: “./imagesForCart/programmingBooks/DesignPatterns.jfif”
inCart: 1
inStock: 39
name: “Design Patterns”
price: 9.99
tag: “DesignPatterns”
[[Prototype]]: Object

how to map a json object into another new object

i have a payload response which goes like:

"requirementDetails": {
            "requirementId1": "A",
            "requirementId2": "B",
            "requirementId3": "C",
            "requirementId4": "D",
            "requirementId5": "E",
            "requirementId6": "",
            "requirementId7": "",
            "requirementId8": "",
            "requirementId9": "",
        }

and i want to create new array of the requirements which will not take the blank requirements using javascript map function and i want the resultant array to look like this:

data = [ "A","B","C","D","E"]

can anybody please help me out.

Chrome Extension “Uncaught Type Error: Cannot read properties of undefined (reading ‘query’) error”. querry property there was a mistake

I am trying to develop an extension for chrome. I did the necessary operations in the Process.js file. The codes worked but I got an undefined query error. This error did not prevent the code. There was a problem only in the share part in Google Slides. what do you think is the reason?
The system is working, but how can i prevent that warning ?
Please help me ?

Share google slides button not working. It works when I remove the plugin.

process.js

chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {
    let url = tabs[0].url;
    url = url.replace('//', ';;').replace(/[/]/g, ';');
    let pageTitle = tabs[0].title;
    pageTitle = pageTitle.replaceAll("'", '*');
    pageTitle = pageTitle.replaceAll('"', '**');
    pageTitle = pageTitle.replace('//', '__').replace(/[/_]/g, '_');

});

google Slides and chrome extension image

chrome extension error log image

manifest.json

{
  "name": "DergiPark",
  "description": "This is a DergiPark Product. Powered by DergiPark.",
  "content_scripts": [
    {
      "js": [
        "/js/jquery.min.js",
        "/js/alert_util.js",
        "process.js"
      ],
      "css": [
        "/css/bootstrap.css"
      ],
      "matches": [
        "http://*/*",
        "https://*/*"
      ]
    }
  ],
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },
  "icons": {
    "48": "icons/DP-02.png",
    "128": "icons/DP-02.png"
  },
  "action": {
    "default_icon": {
      "16": "icons/DP-02.png",
      "24": "icons/DP-02.png",
      "32": "icons/DP-02.png"
    },
    "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab", "tabs"
  ]
}

FormData not sending File object through Post request

I am making an axios.post() request in my Vue component to send some formData holding a media File to upload through a PHP script. I know the file object is being appended correctly as I log the data before the request here:

// this.postMedia is a Vue array holding any post media objects to be uploaded
this.postMedia.forEach((mediaObj, index) => {
    formData.append('media[' + index + ']', mediaObj.media);
    formData.append('mediaType[' + index + ']', mediaObj.mediaType);
});

// Logging formData
for (let p of formData.entries()) {
    console.log(p);
}

This logs the information of the file object and the corresponding media type as expected.

// This is the media data
File {
    lastModified: 1627299857401
    lastModifiedDate: Mon Jul 26 2021 07:44:17 GMT-0400 (Eastern Daylight Time) {}
    name: "test-image.jpg"
    size: 12295
    type: "image/jpeg"
    webkitRelativePath: ""
}

// This is the mediaType data
1

I am then passing this data through an axios request and logging the response data as follows:

// Vue.js file
axios.post('/api/createPostV2', formData, config)
.then(success => {
    console.log(success.data);
})
.catch(function(err) {
    console.log(err.response);
});


// PHP file being requested (/api/createPostV2)
public static function createPostV2(Request $request)
{
    // Just return request to check data
    return $request->all();
}

Here is what gets logged:

media: Array(1)
    0: {}
    length: 1
    [[Prototype]]: Array(0)
mediaType: ['1']

So it is passing the media array, but the actual file is not being passed as you can see by the empty object at index 0. As you can see the mediaType is passed correctly, keep in mind both ‘media’ and ‘mediaType’ are arrays to support uploading multiple files. Am I missing something here? Why is the file data being lost when I am passing it through formData?

jquery ajax header sending error Access to XMLHttpRequest at https://discord.com/api/guilds/1234567890

<script>
    const URL = "https://discord.com/api/guilds/899175503565553714";
    $.ajax({
        url: URL,
        type: "GET",
        headers: { Authorization: 'Bot ' + token } })
</script>

Here is my code

index.html:1 Access to XMLHttpRequest at 'https://discord.com/api/guilds/899175503565553714' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

How can I send headers and receive values ​​successfully with jquery ?