Chrome extension httpRequestHeaders with manifest 3

I’m updating a Chrome extension from manifest 2 to manifest 3.
I have some troubles with sending dynamic httpRequestHeaders.
It’s possible to send these dynamic headers but some headers are blocked ie. “cookies”

So it’s possible to send for example:

$.ajax({
   type: "POST",
   url: "SOMEURL",
   data: {
      "id": idValue,
   },
   headers: {
      "blabla": "HARDVALUE"+dynamicValue
   },
   success: ...

and it’s not possible to send

$.ajax({
   type: "POST",
   url: "SOMEURL",
   data: {
      "id": idValue,
   },
   headers: {
      "cookie": "HARDVALUE"+dynamicValue
   },
   success: ...

I tried to use a declarativeNetRequest with the rules.json-file but it’s hard-coded and not possible to use a dynamic value

[
  {
    "id" : 1,
    "priority": 1,
    "action" : { "type" : "modifyHeaders",
      "responseHeaders": [
        { "header": "Cookie", "operation": "set", "value": "hardCodedValue" }
      ]
    },
    "condition" : {
      "urlFilter" : "SOMEURL",
        "resourceTypes" : ["xmlhttprequest"]
    }
  }
]

This last one is sending the header but I can’t use a dynamic custom variable or something. Has anybody a solution for this?

A form based on a Jquery function not working on mobile only

We have a WordPress/Woocommerce site and we have a form (Advanced products field plugin) for customers to fill extra product options. We are using a jQuery function to make the form a multi-step form and it has been working fine on mobile and desktop. They press on a button (Continue) to proceed to next step and get an Add to Cart button at the last step.

Suddenly the form stopped working on mobile only, the jQuery is not working correctly on mobile. Whenever we change screen size or open the website on mobile the form works differently, the Add Cart Button shows at first step and the continue button does not go to next step. When we refresh on desktop the form works perfect!

We are not sure what could cause this type of issue. We tried debugging and it is not plugin or theme related.

You check this product https://staging.f1mats.com/product/f1hybrid-series-premium-car-floor-mats-set/ as an example.

The jQuery was provided by the plugin author and it always worked good.

add_action('wapf_before_wrapper', 'wapf_before_wrapper');

function wapf_before_wrapper($product) {
    ?>
     
    <div class="wapf-progress">
      
        <div class="wapf-progress-bar"></div>
        <div class="wapf-progress-steps"></div>
    </div>
   
 <div class="wapf-step-back"> <a class="button wapf_btn_prev" style="display:none" ><?php _e('Back','sw-wapf'); ?></a></div>
    <div class="wapf-updatedetails" style="display:none"> <a class="button wapf_btn_update"  ><?php _e('Edit your selection','sw-wapf'); ?></a></div>
    <?php
}

add_action('wapf_before_product_totals', 'wapf_before_product_totals');

function wapf_before_product_totals($product) {
    ?>
    <div class="wapf_step_buttons">
        
        <button class="button wapf_btn_next"><?php _e('Continue','sw-wapf'); ?></button>
    </div>
    <?php
}

/***jquery***/


add_action('wp_footer','wapf_steps_script');

function wapf_steps_script(){
?>
<script>
jQuery( function($) {
    var steps = $('.wapf-section.step');
    if(!steps.length) return;
    var maxSteps = steps.length;
    var $prev = $('.wapf_btn_prev');
    var $next = $('.wapf_btn_next');
    var $stepList = $('.wapf-progress-steps');
    var $bar = $('.wapf-progress-bar');
    var $cart = $('div.quantity,[name="add-to-cart"]');
    var $progress = $('.wapf-progress');
    var currentStep = 1;
    
    for(var i = 1; i <= maxSteps; i++) {
        var $div = $('<div>');
        if(i === 1) $div.addClass('active');
        $stepList.append($div);
    }
                            
    var post = function(e) {
                var visibleStepLi = $stepList.find('div:visible');
                var idx = $stepList.find('div').index(visibleStepLi.eq(currentStep-1));
                idx = Math.max(0,idx);
        var max = visibleStepLi.length;
        if(e) e.preventDefault();
        steps.hide();
        steps.eq(idx).css('display','flex');
        
        $stepList.find('div').removeClass('active').eq(idx).addClass('active').prevAll().addClass('active');
        if(currentStep >= max) {
            $cart.show();
        } else $cart.hide();
        
        $bar.css('width', (currentStep-1)*(100/(max-1))+'%');
        
        $prev.hide();
        $next.hide();
        if(currentStep < max) $next.show();
        if(currentStep > 1) $prev.show();
    }
    
    var isValid = function() {
        
        var $inputs = steps.eq(currentStep-1).find(':input');
        
        for(var i = 0; i < $inputs.length; i++) {
            if(!$inputs[i].checkValidity()) return false;
        }
        return true;
    }
    
    $prev.on('click', function(e) {
        currentStep--;
        post(e);
    });
    
    $next.on('click', function(e) {
        var valid = isValid();
        if(isValid()) {
            currentStep++;
            post(e);
        }
    });
    
    $(document).on('wapf/dependencies', function(){
        $stepList.find('div').removeClass('wapf-hide');
        steps.each(function(i,s) {
            var $s = $(s);
            if($s.hasClass('wapf-hide')) $stepList.find('div:eq('+i+')').addClass('wapf-hide');
        });
        if($stepList.find('div:not(.wapf-hide)').length <= 1)
            $progress.hide();
        else $progress.show();
        
        post();
    });

        // Block enter key to prevent jumping to another step on accident.
    steps.find('input, select').keypress(function(event) { return event.key != 'Enter'; });
});
</script>
<?php
}

useState executing before another function

I am trying to setRes() as respond which is the result for a login request but Res is not setting
This is the function:

  const [res, setRes] = useState({ auth: false, type: '', reason: '' })

  const Handlelogin = async (e) => {
    e.preventDefault();
    const respond = await login(e)
    setRes(respond)
  }

respond should return an object like this :

result={auth:false, reason:"Wrong Credentials!",type:'error' }; 

or

 result={auth:true, type:response.data.auth}; 

I tried console.log() for respond and the result is correct but the setRes(respond) is not working.
Any ideas?

Unable to click on a tag- selenium

While trying to click on a link using Newrelic synthetic monitor(selenium based), it appears to have started failing since few days. The screenshot of error shows the control hovered over the link but didnt click.

.then(function() {
  log(10, 'clickElement "Dashboard"');
  return $browser.waitForAndFindElement(By.xpath('//*[contains(text()," Dashboard ")]'), DefaultTimeout); })
.then(function (el) { el.click();  })

Element:

<a _ngcontent-avd-c527="" cdkmonitorelementfocus="" rel="noopener noreferrer" queryparamshandling="merge" class="name trimmedTextWithEllipsis ng-star-inserted" href="**" target="_self" pbi-focus-tracker-idx="17"> Dashboard <!----><!----><!----><!----></a>

Looping through a folder in javascript

I’m making an art gallery for my website, and to load the images i need to loop through all of them. I’ve tried fs but i’ve been told that node modules like fs don’t work in browsers. Is there another way of looping through a folder and getting the directory of the image in a browser?

FullCalendar with ES6 Build System: “initialView” and “headerToolbar” ignored

I’m moving my script tags based FullCalendar setup to an ES6 build system one and am facing a weird bug that I can’t fix.

So I import the FullCalendar class and plugins in my main-calendar.js file like this:

import { Calendar } from '@fullcalendar/core';
import listPlugin from "@fullcalendar/list"
import dayGridPlugin from "@fullcalendar/daygrid"
import timeGridPlugin from "@fullcalendar/timegrid"

then, in the same file, I create my calendar object like this:

    var calendar = new Calendar(calendarEl, {

        plugins: [listPlugin, dayGridPlugin, timeGridPlugin],

        initialView: "list",

        headerToolbar: {
            left: 'prev,next today',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
        }

    })

a calendar is rendered BUT:

  • headerToolbar is always ignored. I can add any value to left, center and right but what will be rendered will always be a date on the left and today+prev,next on the right
  • initialView also always ignored
  • the only thing i can change is the initial view by changing the order of the plugins in plugins property array. I can switch between timeGridPlugin and dayGridPlugin and it will change the initial view. listPlugin however, if put first in the array doesn’t change anything.

It’s a Laravel website using Webpack/Laravel mix. My Webpack config:

mix.js('resources/js/Calendar/main-calendar.js', 'public/js')
mix.postCss('node_modules/@fullcalendar/core/main.css', 'public/css/fullcalendar/core.css')
    .postCss('node_modules/@fullcalendar/daygrid/main.css', 'public/css/fullcalendar/daygrid.css')
    .postCss('node_modules/@fullcalendar/timegrid/main.css', 'public/css/fullcalendar/timegrid.css')
    .postCss('node_modules/@fullcalendar/list/main.css', 'public/css/fullcalendar/list.css')
mix.sass('resources/sass/calendar.scss', 'public/css')

I’m kindof clueless. I got no errors in my Chrome console and I’ll have to rollback to a script tags approach if I can’t fix this.

JavaScript getElementByID from Array [closed]

Hi I am trying to get div from API array of clicked index by using getElementById as shown in the code, but its not working

can anyone help me

advance thanks

**API Array**
address:Array[3]
 0:Object
 1:Object
 2:Object

 **HITL Code**
 <div class="col-lg-4 col-md-6 col-sm-12 mt-3" v-for="(address, index) in address"
 :key="index" id="address-display">

  **JS Code**
  this.address[index].document.querySelector('#address-display')

cluster module to interact with child processes (workers) [closed]

Please help In this exercise, you will use the cluster module to interact with child processes (workers).

A worker has been implemented at workerPath. It uses CPU-heavy computing logic. The worker is waiting for the input message from the primary cluster process. It then calculates the result, returns it, and exits.

Your goal is to implement the asynchronous function doCalculations(inputs, workerPath) that sends inputs to the worker and returns the calculation results.

  • inputs is a list containing the string input(s) to be sent.
  • workerPath is a string representing the path to the worker file.
  • Your function should return a Promise object that resolves to an array of results.
  • The calculations should run in parallel.
  • The order between the inputs and outputs should be preserved.
// JavaScript code belowconst 
cluster = require("cluster");
/** 
* 
* @param {string[]} inputs 
* @param {string} workerPath 
* @returns {Promise<Array<string | number>} calculation results returned from workers 
*/
async function doCalculations(inputs, workerPath = "/tmp/deps/worker") {    
  // Your code goes here    
  const result = []; // = calculate(inputs)    
  return result;
}
doCalculations(['hello', 'world']).then(console.log).catch(console.error)

onChange event inside loop is only passing 0th index

The following code is a input component which uploads an image and I am using a function “handleImageChange” to trigger onChange event. it is inside a loop

{images.map((x,i) => (
    <Grid item>
           <Input
              accept="image/*"
              id="change-image-file"
              required
              type="file"
              onChange={(e) => handleImageChange(e, i)}
           />
    </Grid>
)}

 const handleImageChange = (e, index) =>{
       conole.log(index)   // whichever index I click it always returns 0
       conole.log(e.target.files[0])  // however e.target.value works alright
 }

this is the image in correspondence with the code where I am clicking the 2nd image button but still getting the index 0

I am using React 18, Material UI 5, and the “Input” & “Grid” is from material UI which resembles HTML “input” & “div” respectively.

Firebase cloud functions : Delete multiple documents on userDelete

I would like to be able to delete all of a user’s documents when deleting his account. I would like to do this on the backend side with cloud functions.
This similar post doesn’t really answer my question (because I need to delete documents from multiple collections)

Here is the structure of my collections:

users 
  | uid
      | email: [email protected]


orders 
  | docId
      | createdBy: uid
      | …
      | …

Here is my function:

const userDeleted = functions.auth.user().onDelete(user => {
  // get user doc in users collection then remove it
  const usersRef = db.collection("users").doc(user.uid);
  usersRef.delete();
  
  // get all user’s doc in orders collection
  const ordersRef = db.collection("orders")
    .where("createdBy", "==", user.uid)
    .get()
    .then(snapshot => {
      snapshot.forEach(doc => {
        ordersRef.doc(doc.id).delete();
      });
    })
    .catch(err => {
      console.log("Error getting documents", err);
    });

  return Promise.all(usersRef, ordersRef);
})

I need to iterate through the orders collection and find the documents that have the correct uid in the “createdBy” property and then delete them. I feel like I can’t delete multiple things at once during onDelete, and I couldn’t find anything concrete in the documentation.

What am I doing wrong?

How to get a div knowing the class name from Element.classList in Javascript

I have this variable var which has a classList with some classes. Let’s say there is a class in there called “ssp“. How can i get this class only having the var and knowing the name of the class.
I can imagine that it should ne something like var.classList.get("ssp") and in my mind the get() function should return the element but I don’t think there is such method. So does anyone know how to do this?

In my case this is my code:

function newOption(father) {
    // here there should be this 'questionaire' div which has a classlist and one of those is called 'question'
    var father = document.getElementById('questionaire').classList.item(); // here i am trying to access it

    // here i am just adding another class to the father
    const op = document.createElement('div');
    op.classList.add("option");
    op.innerHTML = '<div contenteditable="true">Option</div><input type="checkbox" class="box">';
    father.appendChild(op);
}

How can i fix CORS error firebase function

I currently have a CORS problem that I can’t solve, here is my code:

gogologo.js

const souscription = async (req, res) => {
  if (!req.body.data || !req.body.data.souscrireParams) {
    console.error('souscription  input error')
    res.json({ data: { error: 'souscription input error' } })
    return

  }
  const souscrireParams = req.body.data.souscrireParams
  console.log('souscription:', JSON.stringify(req.body.data.souscrireParams))

  var data = JSON.stringify(souscrireParams)
  const headers = {
    'x-api-key': apiKey,
    'Content-Type': 'application/json'
  }
  var reqConfig = {
    method: 'post',
    url: 'url',
    headers: headers,
    data: data
  };
  console.log("reqConfig = ", reqConfig)
  try {
    const response = await axios(reqConfig)
    const result = response.data
    if (result.resultat === 'success') {
      res.json({ data: result })
    } else {
      const msg = {
        to: 'mail',
        from: 'mail',
        subject: 'souscription Fail',
        html: `deal <br><br> ${JSON.stringify(souscrireParams)}<br><br>Error:<br><br>`,
      }
      sgMail.setApiKey(sgKey)
      await sgMail.send(msg)
      res.json({ data: { error: { message: 'souscrire error' } } })

    }

  } catch (error) {
    console.log('error message : ', error.message)
    console.log('error  : ', error)
    const msg = {
      to: 'mail',
      from: 'mail',
      subject: 'souscription fail',
      html: `deal <br><br> ${JSON.stringify(souscrireParams)}<br><br>Error:<br><br>${JSON.stringify({ error: error.message })}`,
    }
    sgMail.setApiKey(sgKey)
    await sgMail.send(msg)
    res.json({ data: { error: error.message } })
  }

}

exports.souscription = souscription

index.js

exports.souscription = functions.runWith({
   vpcConnector: 'app-functions-connector',
   vpcConnectorEgressSettings: 'ALL_TRAFFIC'
}).https.onRequest(async (req, res) => {
  console.log('souscription IP:', await publicIp.v4())
  cors(req, res, async () => {
    gogologo.souscription(req, res)
  })
})

when I press the subscribe button, it displays an error message “Access to fetch at ‘url genereted by firebase function’ from origin ‘url app’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.”
with a post error.

Reduce to map of type typescript

I have this configurations

type Option = {
  value: any,
  label: any
}

And

export interface Role {
  id: number
  name: string
}

Then I have Roles

const roles:Role[]:[
{id:1,name:'name1'},
{id:2,name:'name2'},
{id:3,name:'name3'}
]

I want to extract Option[] from that roles dataset. How do i do it in javascript?

In java I could do

roles.stream().map(role->new Option(role.id,role.name)).collect(collectors.toList());