Selenium Node.js: How to click the same button on several overlapping elements?

I am working with Selenium and have an issue by closing several HTML Elements, which have the same “close” button. These elements are overlapping each other. My idea was to loop through them and close one by one, but it seems not to work.

First I get all “close” buttons:

let by = By.className("jsPanel-btn jsPanel-btn-close jsPanel-btn-md");
let panelsCloseBtns = await this.getElements(by); //custom func to get close button by xpath

It returns array of Selenium Elements.

Then I have tried 3 approaches, but it works only with the first element:

Using actions:

// Close buttons one by one
for (let i=0; panelsCloseBtns.length; i++) {
    if (i === panelsCloseBtns.length) break;
    try{
        await this.driver.actions().mouseMove(panelsCloseBtns[i]).click().perform();
    }catch(ElementClickInterceptedError) {
        await this.driver.actions().mouseMove(panelsCloseBtns[i]).click().perform();
    }
}

It clicks the first element and then I get the error of ElementClickInterceptedError

Using executeScript

for (let i=0; panelsCloseBtns.length; i++) {
    if (i === panelsCloseBtns.length) break;
    await this.driver.executeScript(`arguments[${i}].click();`, panelsCloseBtns[i]);
}

The same result as by actions

The third is just click the button

for (let i=0; panelsCloseBtns.length; i++) {
    if (i === panelsCloseBtns.length) break;
    panelsCloseBtns[i].click();
}

The same result as by actions

I am not sure, how to solve this issue.

Javascript Simple AddEvent Listener

I’m trying to do a simple Event Listener in javascript. The HTML code is the following:

 <!DOCTYPE html>
 <html>
 <head>
 <title>Page Title</title>
 </head>
 <body>

 <button id="getNFT">Click Me</button>

 <script scr="index.js"></script>
 </body>

 </html>

I’m basically just trying to have an On Click event listener on the getNFT button. I’ve declared the event in the index.js that looks like this:

  window.onload = function () {
  var buttonElement = document.getElementById("getNFT");


  if (buttonElement) {
  buttonElement.addEventListener('click', skriv);
  }

  function skriv() {
  alert("Hello ");
  }
  }

But when i click the button, nothing happens…

setTimeout is not executing inside if statement

Settimeout is not executing I want to navigate using the use navigate hook after successful login. The toast message shows but set timeout is not executed and user is not navigated after successful login


  const handleSubmit = async (e) => {
    e.preventDefault();
    const response = await fetch("http://127.0.0.1:80/api/auth/signin", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        name: credentials.name,
        password: credentials.password,
      }),
    });
    console.log(credentials.name,credentials.password)
    const json = await response.json();
    console.log(json);
    if (json.success) {
      // Save the auth token and redirect
      localStorage.setItem("token", json.authtoken);
      toast.success("You are being redirected to home page", {
        position: "top-right",
        autoClose: 2000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined,
        theme: "dark",
      });
      setTimeout(() => {
        navigate("/mynotes");
      }, 3000);
    } else {
      toast.error("Invalid credentials");
      setError(true);
    }
  };


Trying to get reddit’s api to works in node JS, return error 403. where am i wrong?

I’m working on a node project that requires to use the reddit API.

My probleme here is that when i try to do a api call, it return 403.

The thing is that for some api routes, it works fine but not for thoses i want to use.

Here’s my code :

const axios = require('axios');

const redditClientID = 'the id'
const redditClientSecret = 'the secret'

module.exports = function(app) {
    app.get('/reddit', function(req, res) {
        res.redirect(`https://www.reddit.com/api/v1/authorize?client_id=${redditClientID}&response_type=code&state=RJIV5oTRU27BBNaPpqkU&redirect_uri=https://localhost:3000/reddit/callback&duration=temporary&scope=identity,submit,save,privatemessages,vote`)
    });

    app.get('/reddit/callback', (req, res) => {
        const code = req.query.code
        const encodedHeader = Buffer.from(`${redditClientID}:${redditClientSecret}`).toString("base64")
        axios ({
            method: 'post',
            url: `https://www.reddit.com/api/v1/access_token`,
            data: `grant_type=authorization_code&code=${code}&redirect_uri=https://localhost:3000/reddit/callback`,
            headers: {
                authorization: `Basic ${encodedHeader}`,
                'Content-Type': 'application/x-www-form-urlencoded',
                'User-Agent': 'web:PocArea:V0.1 by Me'
            }
        })
        .then((response) => {
            access_token = response.data.access_token
            console.log(access_token);
            getPostScore(access_token, "wxoezm")
        })
        .catch((err) => {
            res.status(500).json({ message: err });
        });
    })

    function getPostScore(redditKey, postId) {
        return axios({
            method: 'get',
            url: `https://oauth.reddit.com/api/info?id=${postId}`,
            headers: {
                'Authorization': `Bearer ${redditKey}`,
                'User-Agent': 'myBot/0.0.1'
            }
        })
        .then(response => {
            var resp = response.data;
            console.log(resp);
            return;
        })
        .catch(error => {
            console.error(`Error retrieving post ${postId} score: `, error);
        });
    }

    function sendPrivateMessage(redditKey) {
        axios({
            method: 'post',
            url: `https://oauth.reddit.com/api/compose`,
            data: {
                api_type: 'json',
                subject: 'objet du message privé',
                text: 'salut, voici un mp de la part de larea',
                to: 'KumaYes',
            },
            headers: {
                'Authorization': `Bearer ${redditKey}`,
                'User-Agent': 'myBot/0.0.1'
            }
        })
        .then((response) => {
            var resp = response.data;
            console.log(resp);
        })
        .catch((error) => {
            console.error(`Erreur lors de la récupération des issues du dépôt alaborde29/GithubAREA: `, error);
        });
    }
}

It works for routes like “api/v1/me” but for other routes i’m kinda lost.

I’ll use the two function at the bottom (sendMessage and getPostScore)

Am I doing it wrong ?

Why doesn’t this Event Listener work when I edit the HTML with JS?

here’s some example code to illustrate what im trying to do

    <div id="thing">No</div>
    <script>
        let elt = document.getElementById("thing")
        elt.addEventListener("click", () => elt.innerHTML = "Yes");
        elt.addEventListener("change", () => alert("Running"));
    </script>

I want the second Event Listener to run the callback function when the html of the element is edited

Pass two arrays from ASP to js

am working on kanban list containing ongoing and todo lists with asp and sql
till now i can pass the first list successfully but can’t add the second list “ongo”
my code is below

    <script>
    document.addEventListener('DOMContentLoaded', function () {
        $.ajax({
            type: "POST",
            url: "index.aspx/GetEvents",
            tasks: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        }).done(function (tasks) {
            var DuT = JSON.parse(tasks.d);
            var OpT = JSON.parse(Otasks.d);
            $('#todo-lists-basic-demo').lobiList({
                lists: [
                    {
                        id: 'todo',
                        title: 'TODO',
                        defaultStyle: 'lobilist-info',
                        items: DuT,
                    },
                    {
                        id: 'doing',
                        title: 'DOING',
                        defaultStyle: 'lobilist-default',
                        items: OpT,
                    },
                ]
            });
        });
    });
</script>

        public class Task
    {
        public string title, description, dueDate;
    }
    public class Ongo
    {
        public string title, description, dueDate;
    }
    [WebMethod]
    public static string GetEvents()
    {
        var tasks = new List<Task>();
        var Otasks = new List<Ongo>();
        String sqlconn = System.Configuration.ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(sqlconn))
        {
            using (SqlCommand SqC = new SqlCommand("Select titl,dscr, due FROM KNtsk WHERE opnd = 1 Order by due", con))
            {
                con.Open();
                using (SqlDataReader sdr = SqC.ExecuteReader())
                {
                    if (sdr.HasRows)
                    {
                        while (sdr.Read())
                        {
                            tasks.Add(new Task()
                            {
                                dueDate = DateTime.Parse(sdr["due"].ToString()).ToString("d"),
                                title = sdr["titl"].ToString(),
                                description = sdr["dscr"].ToString()
                            });
                        }
                    }
                }
                con.Close();
            }
            using (SqlCommand SqC = new SqlCommand("Select titl,dscr, due FROM KNtsk WHERE opnd = 0 Order by due", con))
            {
                con.Open();
                using (SqlDataReader sdr = SqC.ExecuteReader())
                {
                    if (sdr.HasRows)
                    {
                        while (sdr.Read())
                        {
                            Otasks.Add(new Ongo()
                            {
                                dueDate = DateTime.Parse(sdr["due"].ToString()).ToString("d"),
                                title = sdr["titl"].ToString(),
                                description = sdr["dscr"].ToString()
                            });
                        }
                    }
                }
                con.Close();
            }
            var stz = new JavaScriptSerializer();
            return stz.Serialize(tasks);
        }
    }

Its working fine when i remove “var OpT = JSON.parse(Otasks.d);” from the script i know am doing some thing wrong passing those two arrays

How to make the computer pick another random Selection after the player chooses their choice?

After picking Rock, Paper, or scissors, the computers choices stays the same. I want the computer choice to change after the player makes their choice instead of it just staying at one choice.

For example if the player picks “rock” and the computer picks “scissors”, the computers choice would stay at scissors until i refresh the screen.

here is my javascript code:

my code
`//UI
`let userScore = 0;
let compScore = 0;

const userScoreSpan = document.getElementById("userScore");
const compScoreSpan = document.getElementById("compScore");
const rockDiv = document.getElementById("r");
const paperDiv = document.getElementById("p");
const scissorsDiv = document.getElementById("s");
const results = document.getElementById("result");

//UI

rockDiv.addEventListener("click", function () {
play("rock");
});
paperDiv.addEventListener("click", function () {
play("paper");
});
scissorsDiv.addEventListener("click", function () {
play("scissors");
});

// How the game functions
const options = ["rock", "paper", "scissors"];
const computerSelection = computerPicks();

function computerPicks() {
const choice = options[Math.floor(Math.random() * options.length)];
return choice;
}

function play(playerSelection) {
if (playerSelection == computerSelection) {
results.innerHTML = `Its a tie`;
} else if (
(playerSelection == "rock" && computerSelection == "scissors") ||
(playerSelection == "paper" && computerSelection == "rock") ||
(playerSelection == "scissors" && computerSelection == "paper")
) {
userScore++;
userScoreSpan.innerHTML = userScore;
results.innerHTML = `${playerSelection} beats ${computerSelection}`;
} else {
compScore++;
compScoreSpan.innerHTML = compScore;
results.innerHTML = `${computerSelection} beats ${playerSelection}`;
}
}

reactjs 415 unsupported media type

I am calling post api from react –

fetch(url, {
        method : 'POST',
        body : JSON.stringify(payload),
        headers: {
            'Content-Type' : 'application/json',
            'Accept' : 'application/json',
        },

    })
    .then(response => console.log(response))
    .catch(error => console.error(error))

But I am receiving error –

415 Unsupported mediatype

I tried with

'Content-Type' : 'application/json; charset=utf-8',

But this also not worked.

Api is responding 200 with expected json output when hit from swagger.

Form focus on custom element when required hidden field is not filled

I have a form with a hidden required input element. I will be setting the value of this input through javascript based on some other computations.

If the value is empty and the form submits, I want the .focusable div to be focused instead.

Try removing the hidden attribute from the example below and submit the form (without entering any value in the input) to see what I mean. If the value of the hidden input is empty, the form should focus on the div instead of the input element. How can I do this using javascript?

.focusable {
  padding: 12px;
  border: 1px solid green;
  margin: 10px;
  border-radius: 3px;
}

.focusable:focus,
focusable:focus {
  outline: 2px solid green;
}

button {
  margin: 10px;
  padding: 12px;
  border-radius: 3px;
  border: 1px solid black;
  cursor: pointer;
  width: 150px;
}

form {
  text-align: center;
}
<form>
  <input required hidden />
  <div class="focusable">
    This div should focus when form is submitted
  </div>
  <button type="submit">Submit</button>
</form>

How do I open a session stored in local cache into a new window?

This is my script which works correctly to save the sessionID key/value into local storage.

function saveSession() {
  // get document name
  var userInput = $('#docName').val();

  // check if document name is valid
  if (userInput === "") {
    alert("Please enter a document name.");
    return;
  }

  // create a unique key using the current timestamp
  var key = 'pwaSessionID-' + Date.now();

  // save session with the unique key
  localStorage.setItem(key, userInput);

}

I have another well-working script to open and view the cached sessions like this

function openFolder (){

  $("#OPENGREETER").removeClass("JAVA⦘HIDDEN");


  // Get the container for the saved files
var container = $('.DOCGRID');

// Loop through the local storage items
for (var i = 0; i < localStorage.length; i++) {
  var key = localStorage.key(i);

  // Check if the key starts with 'pwaSessionID' (to filter out other local storage items)
  if (key.startsWith('pwaSessionID')) {
    var sessionName = localStorage.getItem(key);
    var sessionKey = key;

    // Create a new element for the session name
    var button = $('<button>').text(sessionName).attr('data-session-key', key);
    button.click(function() {
      openDoc(this);
    });


    // Add the session name to the container
    container.append(button);
  }
}
}

I have a script to open the window which looks like this.

function openDoc(button) {
  // Get the text of the clicked button
  const sessionID = $(button).data('session-key');

  // Open the PWA session with clicked text as ID
  window.open(`WEB.ADDRESS.DELETED.FOR.PRIVACY/${sessionID}`,"_blank","toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=yes, width=900, height=700");
}

The problem with this is that it assumes that cached session can be open by simply appending their sessionID to the end of a URL. But if that is not the case then HOW IN THE WORLD do I open a window containing a cached session?

Two Dimensional array for Google sheets get data in and out of array

Basically I want to load a table into an Array in Google Sheets in VBA this would be easy. Then I want to search the array and find text and log the rows which that data is in.

In VBA this is what I would do.

Dim stArray(11, 1650) As String
Dim iRowLast As Int= 1650; Dim iColLast As Int = 10
Dim wsRaw as Workbook
Set wsRaw = Sheets("Map"): 

* Get the Array data from table *
For xRow = 0 To iRowLast
    For yRow = 0 to iColLast
    stArray(xRow, yRow) = wsRaw.Cells(xRow+1, iCol).Value
    Next yRow
Next xRow

* Get the Array data from table *
For xRow = 0 To iRowLast
    For yRow = 0 to iColLast
    stArray(xRow, yRow) = wsRaw.Cells(xRow+1, iCol).Value
    Next yRow
Next xRow
For xRow = 0 To iRowLast
    For yRow = 0 to iColLast
    wsMap.Cells(xRow, yRow).Value = pdArray(xRow+1, iCol+1)
    Next yRow
Next xRow

I tried something similar in Sheets and quickly found out that Multidimentional arrays don’t exist.

I did find but don’t know how to add to this array.

function Create2DArray(rows) 
{
    var arr = [];
    for (var i=0;i<rows;i++) 
    {
        arr[i] = [];
    }
return arr;
}

React : Filter and Parse object in Array

I have JSON structure which I need to Map, Parse and Filter based on some attribute value to find out which object is containing that value so I can get other attributes of the same object and write my logic.

Below is the JSON Structure:

{
    "methods": [
        {
            "extension_attributes": {
                "time_slots": [
                    "{"display_name":"Today","date":"3\/3\/23","internal_date":"2023-03-03","disabled":0}},"timezone":"Asia\/Dubai","shipping_identifier":"today","selected":1,"disabled":0}",
                    "{"display_name":"Tomorrow","date":"3\/3\/23","internal_date":"2023-02-02","disabled":0}},"timezone":"Asia\/Dubai","shipping_identifier":"today","disabled":0}"
                ]
            }
        }
    ]
}

I have tried to map the JSON like below :

    filteredShippingMethods?.map(mapDeliveryDates)

    const mapDeliveryDates = (deliveryDate) => {
      return deliveryDate?.extensionAttributes?.timeSlots?.map((timeSlot) => {
      const deliveryDateParsed = JSON.parse(timeSlot)
      console.log ('deliveryDateParsed', deliveryDateParsed)
      // Above will return the data in like below :
      [![enter image description here](https://i.stack.imgur.com/c6utS.jpg)](https://i.stack.imgur.com/c6utS.jpg)
      // I want to filter the data like below :
      const selectedShippingMethod = [deliveryDateParsed].filter((element) => element?.selected    === 1)
      console.log ('selectedShippingMethod', selectedShippingMethod)
     //Expecting to return only 1 object but it is returning like below:
     [![enter image description here](https://i.stack.imgur.com/OYxyo.jpg)].  (https://i.stack.imgur.com/OYxyo.jpg)
  })}

Could not find a declaration file for module in Vue 3

working with Vue js 3 and Laravel 8 project. in the project installed via npm vue editor js package as following. https://github.com/ChangJoo-Park/vue-editor-js and I have following app.js file
app.js

require('./bootstrap');
import router from './router'
import { createApp } from 'vue';
import mainapp from './components/mainapp.vue';
import common from './common'
import store from './store'
import Editor from 'vue-editor-js/src/index'


createApp({
    components: {
        mainapp,
        
        },
    
}).use(router).use(store).use(ViewUIPlus).use(Editor).mixin(common).mount('#app');

import file import Editor from 'vue-editor-js/src/index' generated following error message

Could not find a declaration file for module 'vue-editor-js/src/index'. 'F:/2021 Technics/vue + laravel/vue 3/fullstack/node_modules/vue-editor-js/src/index.js' implicitly has an 'any' type.
  Try `npm i --save-dev @types/vue-editor-js` if it exists or add a new declaration (.d.ts) file containing `declare module 'vue-editor-js/src/index';

how could I fix this problem?

Change tag value when it required or not

I use a my-select.component in form component.

<div *ngIf="items?.length">
  <select [ngModel]="selectedItem" (ngModelChange)="valueChanged($event)">
    <option *ngFor="let item of items" [value]="item.id">
      {{ item.name }}
    </option>
  </select>
</div>

I need to display when call this on form component as <my-select required></my-select> set the default value as –select–. otherwise <my-select></my-select> –none–.
How to do this?

Import uncaught referenceError in JS

I try to import the function form App.js file to index.js file, but it appears that the import function is uncaught. Noticed that I use type = “text/babel”.

I treid install webpack and other as well but still does not fix the issue.