browser.pages() doesn’t show all tabs

Using puppeteer I click on links that open new tab.

I firstly open one tab and I can list all tabs with browse.pages().

Then I open another tab and I can’t see the new one that I just opened, despite adding a delay to be sure that the tab is loaded.

Here is the newly open tab, it’s a basic auth.

I can’t provide a reproductible code or more screenshots because of cofidentiality for my company.
Can you understand the issue and why I got it ?

Photo Tagging game

I’m making a Where’s Waldo type of Photo Tagging game.

How should I identify where a person is in the image?
If the person was a box I could just store the outer left, outer right, outer bottom and outer top coordinates, and when a use clicks on the image, I would check if the coordinates of that click were within the coordinates of the box.

Commerce JS, generateToken returning “Material-UI: A component is changing the controlled value state of Select to be uncontrolled.”

This is where i generate the token

import React, { useState, useEffect } from 'react';
import { Paper, Stepper, Step, StepLabel, Typography, CircularProgress, Divider, Button } from '@material-ui/core';

import { commerce } from '../../../lib/commerce';
import useStyles from './styles';
import AddressForm from '../AddressForm';
import PaymentForm from '../PaymentForm';

const steps = ['Shipping address', 'Payment details'];

const Checkout = ({ cart }) => {
    const [activeStep, setActiveStep] = useState(0);
    const [checkoutToken, setCheckoutToken] = useState(null);
    const classes = useStyles();

useEffect(() => {
    if (cart.id) {
        const generateToken = async () => {
            try {
                const token = await commerce.checkout.generateToken(cart.id, { type: 'cart' });

                setCheckoutToken(token)
            } catch (error){
                console.log(error);
            }
        };

        generateToken();
    }

}, [cart]);

const Confirmation = () => (
    <div>
        Confirmation
    </div>
)

const Form = () => activeStep === 0
    ? <AddressForm checkoutToken={checkoutToken} />
    : <PaymentForm />

return (
    <>
        <div className={classes.toolbar} />
        <main className={classes.layout} >
            <Paper className={classes.paper}>
                <Typography variant='h4' align='center'>Checkout</Typography>
                <Stepper activeStep={activeStep} className={classes.stepper}>
                    {steps.map((step) => (
                        <Step key={step}>
                            <StepLabel>{step}</StepLabel>
                        </Step>
                    ))}
                </Stepper>
                {activeStep === steps.length ? <Confirmation /> : checkoutToken && <Form />}
            </Paper>
        </main>
    </>
)
}

 export default Checkout

Here is my App.js

import React, { useState, useEffect, Fragment } from 'react'
import { commerce } from './lib/commerce';
import { Products, Navbar, Cart, Checkout } from './components';
import { BrowserRouter as Router, Routes, Route} from 'react-router-dom';

const App = () => {
    const [products, setProducts] = useState([]);
    const [cart, setCart] = useState({});

const fetchProducts = async () => {
    const { data } = await commerce.products.list();

    setProducts(data);
}

const fetchCart = async () => {
    setCart(await commerce.cart.retrieve())
}

const handleAddToCart = async ( productId, quantity) =>{
    const { cart } = await commerce.cart.add(productId, quantity);
    
    setCart(cart);
}

const handleUpdateCartQty = async (productId, quantity) => {
    const { cart } = await commerce.cart.update(productId, { quantity });

    setCart(cart);
}

const handleRemoveFromCart = async (productId) => {
    const { cart } = await commerce.cart.remove(productId);

    setCart(cart);
}

const handleEmptyCart = async () => {
    const { cart } = await commerce.cart.empty();

    setCart(cart);
}

useEffect(() => {
    fetchProducts();
    fetchCart();
}, []);

return (
    <Router>
        <div>
            <Navbar totalItems={cart.total_items} />
            <Routes>
                <Route exact path='/' element={<Products products={products} onAddToCart={handleAddToCart} />} />
                <Route exact path='/cart' element={<Cart cart={cart} handleUpdateCartQty={handleUpdateCartQty} handleAddToCart={handleAddToCart} handleRemoveFromCart={handleRemoveFromCart} handleEmptyCart={handleEmptyCart} />} />
                <Route exact path='/checkout' element={ <Checkout cart={cart} />} />
            </Routes>
        </div>
    </Router>
)
}


export default App;

And here is my cart.jsx incase their is anything relevant there

import React from 'react'
import { Container, Typography, Button, Grid} from '@material-ui/core';
import { Link } from 'react-router-dom';

import useStyles from './styles';
import CartItem from './CartItem/CartItem';

const Cart = ({ cart, handleUpdateCartQty, handleRemoveFromCart, handleEmptyCart }) => {
    const classes = useStyles();

    const EmptyCart = () => (
        <Typography variant='subtitle1'>
            You have no items in your shopping cart.
            <Link to='/' className={classes.link}>Add Items!</Link>
        </Typography>
);

const FilledCart = () => (
    <>
        <Grid container spacing={3}>
            { cart.line_items.map((item) => (
                <Grid item xs={12} sm={4} key={item.id}>
                    <CartItem item={item} onUpdateCartQty={handleUpdateCartQty} onRemoveFromCart={handleRemoveFromCart} />
                </Grid>
            ))}
        </Grid>
        <div className={classes.cardDetails}>
                <Typography variant='h4'>
                    Subtotal: {cart.subtotal.formatted_with_symbol}
                    <div>
                        <Button className={classes.emptyButton} size='large' type='button' variant='contained' color='secondary' onClick={handleEmptyCart}>
                            Empty Cart
                        </Button>
                        <Button component={Link} to='/checkout' className={classes.checkoutButton} size='large' type='button' variant='contained' color='primary'>
                            Checkout
                        </Button>
                    </div>
                </Typography>
        </div>
    </>
);

// Wait for cart to load items
if(!cart.line_items){
    return '...loading';
}

return (
<Container>
    <div className={classes.toolbar} />
    <Typography className={classes.title} varaint='h3' gutterBottom >Your Shopping Cart</Typography>
    { !cart.line_items.length ? <EmptyCart /> : <FilledCart />}
</Container>
)
}
export default Cart

[error messages][1]
[1]: https://i.stack.imgur.com/vlard.png

Warning: Expected onSubmit listener to be a function, instead got a
value of string type. form
FormProvider@http://localhost:3000/static/js/bundle.js:76722:7
AddressForm@http://localhost:3000/static/js/bundle.js:1096:7 Form div
Paper@http://localhost:3000/static/js/bundle.js:12332:17
WithStyles@http://localhost:3000/static/js/bundle.js:19639:25 main
Checkout@http://localhost:3000/static/js/bundle.js:1332:7
Routes@http://localhost:3000/static/js/bundle.js:67209:7 div
Router@http://localhost:3000/static/js/bundle.js:67146:7
BrowserRouter@http://localhost:3000/static/js/bundle.js:65952:7
App@http://localhost:3000/static/js/bundle.js:347:82

Warning: A component is changing a controlled input to be
uncontrolled. This is likely caused by the value changing from a
defined to undefined, which should not happen. Decide between using a
controlled or uncontrolled input element for the lifetime of the
component. More info: https://reactjs.org/link/controlled-components
input SelectInput@http://localhost:3000/static/js/bundle.js:13482:19
div InputBase@http://localhost:3000/static/js/bundle.js:8257:25
WithStyles@http://localhost:3000/static/js/bundle.js:19639:25
Input@http://localhost:3000/static/js/bundle.js:9146:26
WithStyles@http://localhost:3000/static/js/bundle.js:19639:25
Select@http://localhost:3000/static/js/bundle.js:13182:26
WithStyles@http://localhost:3000/static/js/bundle.js:19639:25 div
Grid@http://localhost:3000/static/js/bundle.js:7352:29
WithStyles@http://localhost:3000/static/js/bundle.js:19639:25 div
Grid@http://localhost:3000/static/js/bundle.js:7352:29
WithStyles@http://localhost:3000/static/js/bundle.js:19639:25 form
FormProvider@http://localhost:3000/static/js/bundle.js:76722:7
AddressForm@http://localhost:3000/static/js/bundle.js:1096:7 Form div
Paper@http://localhost:3000/static/js/bundle.js:12332:17
WithStyles@http://localhost:3000/static/js/bundle.js:19639:25 main
Checkout@http://localhost:3000/static/js/bundle.js:1332:7
Routes@http://localhost:3000/static/js/bundle.js:67209:7

Get File Created Date from Dropbox JS SDK/API

I want to extract the file created date from the DROPBOX API using JS. I have tried to fetch the modification date but not able to find the file creation date

Any help is greatly appreciated.

<!doctype html>
<html>
<head>
  <title>Dropbox JavaScript SDK</title>
<style>
body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  line-height: 1.5;
}
.container {
  display: block;
  width: 90%;
  max-width: 800px;
  margin-left: auto;
  margin-right: auto;
}
.container.main {
  padding-top: 30px;
}
code, .code {
  font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace;
  color: #666;
}
.info {
  font-size: 13px;
  font-style: italic;
  color: #666;
  margin-top: 40px;
}
a {
  color: #007ee5;
}
input {
  border: 2px solid #007ee5;
  border-radius: 3px;
  padding: 8px;
  font-size: 16px;
}
.button, button {
  border-radius: 3px;
  background-color: #007ee5;
  border: none;
  color: #fff;
  font-size: 16px;
  padding: 10px 15px;
  text-decoration: none;
}

.page-header {
  background-color: #007ee5;
  padding: 10px 0 0 0;
}
.page-header .container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 150px;
}
.page-header a {
  color: #fff;
  text-decoration: none;
}
.page-header nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.page-header h1 {
  display: flex;
  align-items: center;
  color: #fff;
  font-size: 17px;
  font-weight: 200;
}
.page-header .logo {
  width: 100px;
  margin-right: 10px;
}
.page-header .view-source {
  font-weight: 200;
  font-size: 12px;
}
.page-header h2 {
  color: #fff;
  font-size: 18px;
  font-weight: normal;
}
</style>
  <script src="https://cdn.jsdelivr.net/npm/promise-polyfill@7/dist/polyfill.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fetch/2.0.3/fetch.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropbox.js/10.27.0/Dropbox-sdk.min.js" integrity="sha512-nTLJySi/DUYzRvvxWOxf31QS5191sN1gpoq6EqGFHPFH0RlM6xOiY6jEp9dmwhDlyFmCmicwLOMnE+fUmo02KQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>
<body>
  <!-- Example layout boilerplate -->
  <header class="page-header">
    <div class="container">
      <nav>
        <a href="/">
          <h1>
            <img src="https://cfl.dropboxstatic.com/static/images/brand/logotype_white-vflRG5Zd8.svg" class="logo" />
            JavaScript SDK Examples
          </h1>
        </a>
        <a href="https://github.com/dropbox/dropbox-sdk-js/tree/main/examples/javascript" class="view-source">View Source</a>
      </nav>
      <h2 class="code">
        <a href="/">examples</a> / basic
      </h2>
    </div>
  </header>

  <!-- Example description and UI -->
  <section class="container main">

    <textarea id="files"></textarea>

  </section>

  <!-- Scripts to run example -->
  <script>
    var form = document.getElementById('basic-form');
    var ACCESS_TOKEN = '<TOKEN_HERE>';
    var dbx = new Dropbox.Dropbox({ accessToken: ACCESS_TOKEN });
    var filesList = document.getElementById('files');
    var li;

      
    function listFiles(path) {
      dbx.filesListFolder({path: path})
        .then(function(response) {
          console.log('response', response)
          var items = response.result.entries;
          var values = [];
              
          for (var i = 0; i < items.length; i++) {
            if(items[i][".tag"] == "file")
            {
              values.push('"'+[path+"/"+items[i].name, items[i].server_modified,items[i].size].join('","')+'"');
            }
            
           
            if(items[i][".tag"] == "folder")
              listFiles(path+"/"+items[i].name)
          }
          document.getElementById("files").innerHTML = document.getElementById("files").innerHTML + "n" + values.join("n")
        })
        .catch(function(error) {
          console.error(error);
        });
    }
    listFiles('')
  </script>
</body>
</html>

Nuxt head not updated on all pages

I just updated Nuxt to latest version (2.15.7) from the 2.8.0 and it looks like the head is not working anymore as expected.

I didn’t change anything on this but it is not working anymore.

My app is universal and so it use SSR.

My nuxt.config.js has some default in the head property, i.e.:

head: {
  title: 'My Global Title'
}

Then, one of my pages, for example the “About us”, has this:

head() {
  return {
    title: 'About us'
  }
}

Once I reload the page, for a very short time, in the tab of the browser I notice the global title, then replaced to the About us. The bad part is that if I view the page source, it has saved the global title and this affect my SEO and also my sharing on socials.

I cannot share a page anymore on Facebook for example, because it continue using the global values rather than the local values set in the pages.

Yes, I’m using hid property on all my descriptions and open graph values, but it has no effect.

So I tried using another library: nuxt-seo, it looks good and detailed, but nothing changed.

I tried to use asyncData to set the $seo and suddenly it worked even if it is suggested, for SSR applications, not to use asyncData to set the head properties and intead using the head that unfortunately is not working as expected.

Is there something I’m missing? I don’t know because it was working fine on the previous version… Maybe something is changed and I’m not aware and I cannot find on any documentation online.

html input element will not update to for loop

The text in the input immediately just skips to 99. Is there any way I can make it display
the i variable, while it’s iterating?

<input id="test" type="text">
<script>
    for(let i = 0; i < 100; i++){
    document.getElementById("test").value = String(i);
  }
</script>

I am making a music template but the music and images are not loading

I am making a music tempelate. This is my code and my query on the top. I am loading this query to loadQuestion but it’s not happening from my computer.

const songs = [
        {
            name: "music-1",
            title: "Bring me back",
            artist: "Honey Singh",
        },
        {
            name: "music-2",
            title: "Ku Ku",
            artist: "Bilal Saeed",
        },
        {
            name: "music-3",
            title: "Mera yaar mila de",
            artist: "Rahat Fateh Ali Khan",
        },
        {
            name: "music-4",
            title: "Sochta hon",
            artist: "Rahat Fateh Ali Khan",
        },
        {
            name: "music-4",
            title: "Ki samjhaiye sajna",
            artist: "Amrinder Gill",
        },
    ];

    const music = document.querySelector("audio");
    const img = document.querySelector("img")
    const play = document.getElementById("play");
    const pause = document.getElementById("pause");
    const title = document.getElementById("title");
    const artist = document.getElementById("artist");
    const next = document.getElementById("next");
    const pre = document.getElementById("pre");
    
    // For Play Function
    play.addEventListener("click", ()=>{
        music.play();
        
        play.style.display="none"
        img.classList.add("animation");
        pause.style.display="inline-block";
    });
    
    // For Pause Functio
    pause.addEventListener("click", ()=>{
        music.pause();
        
        play.style.display="inline-block"
        img.classList.remove("animation");
        pause.style.display="none";
    });
    
    // Changing the music data
    
    const loadSong = (songs) => {
        title.textContent = songs.title;
        artist.textContent = songs.artist;
        music.src = `${window.location.origin}/assets/music/${songs.name}.mp3`;
        img.src = `${window.location.origin}/assets/images/${songs.name}.jpg`;
        console.log(songs[2]);
    }
    
    
    loadSong(songs[2]);

Checkbox event not triggering class toggle on label

Similar questions on stackoverflow but not quite what I need.
So I have a parent div with multiple checkboxes wrapped in labels, I then attached a click even on the parent so it bubbles to every child element. My problem is the class is toggled fine when clicked on the label (its a class that changes the style of the label), but when I click on the actuall little checkbox it does not work since it adds the class to the input and not the label, how would I make it that the class is toggled on label even if the event.target is on the checkbox input

const requiredForm = document.querySelectorAll('.drinos-required')
const requiredCheckbox = document.querySelector('.required-form-input')

const requiredFunction = function(evt) {
  if (!evt.target.classList.contains('drinos-required')) return;
  evt.target.classList.toggle('checkerActive')
}

requiredCheckbox.addEventListener('click', requiredFunction)
.checkerActive {
  background-color: red;
}
<div class="required-form-input">
  <label class="drinos-required">  <input class="drinos-checkbox-required" type="checkbox" name="checkbox" value="value">Electrician</label>
  <label class="drinos-required">  <input class="drinos-checkbox-required" type="checkbox" name="checkbox" value="value">Plumber</label>
  <label class="drinos-required">  <input class="drinos-checkbox-required" type="checkbox" name="checkbox" value="value">Mason</label>
  <label class="drinos-required">  <input class="drinos-checkbox-required" type="checkbox" name="checkbox" value="value">Carpenter</label>
  <label class="drinos-required">  <input class="drinos-checkbox-required" type="checkbox" name="checkbox" value="value">Handyman</label>
  <label class="drinos-required">  <input class="drinos-checkbox-required" type="checkbox" name="checkbox" value="value">Painter</label>
  <label class="drinos-required">  <input class="drinos-checkbox-required" type="checkbox" name="checkbox" value="value">Cleaner</label>
  <label class="drinos-required">  <input class="drinos-checkbox-required" type="checkbox" name="checkbox" value="value">Lawn Care/Landscaping</label>
  <label class="drinos-required">  <input class="drinos-checkbox-required" type="checkbox" name="checkbox" value="value">Tree Service</label>
  <label class="drinos-required">  <input class="drinos-checkbox-required" type="checkbox" name="checkbox" value="value">Pool Service</label>
</div>

JS constructor method returning undefined

I have a constructor method below.

function CreateIncome(name, amt, recurring)
{
    this.name = name;
    this.amt = amt;
    this.recurring = recurring;
}

When I call it in my code here like so:

    let incomeObj = CreateIncome("salary", 5000, true);
    alert(incomeObj.name+" : "+incomeObj.recurring);

I am getting this error:

Uncaught TypeError: Cannot read properties of undefined (reading 'name')

The only reason I can think of for this is that CreateIncome() is returning an empty object that triggers the error when the program attempts to access one of its properties (‘name’ in this case). I’ve debugged my code to the best of my ability and can’t seem to find a logical reason for this happening. I’ve also used almost identical code to this in a previous application that worked correctly which makes this all the more puzzling. Any help would be greatly appreciated.

PS: I am still very new to Javascript so I apologise for any rookie errors.

How do I make code run sequentially in Javascript?

for (0 - 30){
line 1
function call
based on the return of function line 2
line 3
}

My problem is line 1 executes 30 times, then function call executes 1 time and waits for the result, line 3 executes 30 times

I have tried

for (0 - 30){
line 1
function call{
  based on the Boolean return of function 
  change Boolean
}
line 3
}

In this case line 1 executes 30 times, then function call executes 30 times, line 3 executes 30 times, then change boolean run based on the function call

How to Include JavaScript variable in Django URL in template?

I want to include mangaid variable in “{% url ‘manga’ mangaid %}”. Neither ${mangaid} nor mangaid works. How can I do this?

   let input = document.querySelector("#search")
    input.addEventListener("keyup", () => {
      document.querySelector("#results").innerHTML = "";
      let value = (input.value)
      fetch(`searchresponse/${value}`).then((response) => response.json()).then((results) => {
        results.forEach(function (result) {
          let mangaid = (result["id"])
          document.querySelector("#results").insertAdjacentHTML('beforeend', `<a class="result" id="result${mangaid}">${result["title"]}</a>`);
          document.getElementById("result"+mangaid).addEventListener("click", (event) => {
            event.target.href = "{% url 'manga' mangaid %}"
          })
        })
      })
    })

React native typescript useEffect not updating array

Am trying to create a real time voting using Pusher, typescript and react native, but the candidates array is not being updated and displayed on the useEffect function. but when I run the same code lines from a normal vote it works (the candidates array is updated and displayed correctly);

  const [candidates, setCandidates] = useState([]);`

const vote = (id, position,name,name2) => {
 var newVoteData = ({voterName:votingData.voterName,voterId:votingData.voterId,position:position,candidateId:id,candidateName:name});
 setProcessingModal(true);
 fetch('http://172.20.10.4:8000/mobile/vote', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json', 
          },
          body: JSON.stringify(newVoteData),
        })
        .then((response) => response.json())
        .then((data) => {
            if(data.status == "ok"){This block of code works, updates the particular candidate voteCount and setCandidates correctly
                setProcessingModal(false);
                alert("Yay!!! , you have successfully voted");
                const updatedData = candidates.map(x => (x.id === id ? { ...x, voteCount: data.voteCount } : x));//updates votecount on candidate
                
                let newArr = updatedData.sort((x,y) => {return y.voteCount - x.voteCount});
                setCandidates(updatedData);
            }else{
                setProcessingModal(false);
                alert(data)
            }
            
        })
        .catch((error) => {
            setProcessingModal(false);
            alert(error);
          console.error('Error:', error);
        });
          };

the below useEffect function is where am having issues, the array for some reason is not being updated

useEffect(() => { 
     
     const liveUpdateCandidates = (id, voteCount) => {
  
        alert(voteCount);
                const updatedData = candidates.map(x => (x.id === id ? { ...x, voteCount: voteCount } : x));//updates votecount on candidate does not work here
                console.log('afer');
                let newArr = updatedData.sort((x,y) => {return y.voteCount - x.voteCount});
                setCandidates(updatedData);   
        };
     
    //Pusher.logToConsole = true;
    const pusher = new Pusher('3580cab8bee36d295917', {
        cluster: 'eu',
        encrypted: true
    });

    const channel = pusher.subscribe('votebooth-channel');
        channel.bind('App\Events\BoothEvent', function(data) { 
         liveUpdateCandidates(data.candidateId, data.voteCount);
    });

    
    return (() => {
            pusher.unsubscribe('votebooth-channel'); 
            // pusher.unsubscribe('channel_name2');
        }) 
      },[candidates]);

Below is a sample of the returned array

[

{“id”:”3″,”name”:”Kwaku”,”candidateUserId”:null,”gender”:”Male”,”philosophy”:”Good”,”voteCount”:”132″,},
{“id”:”22″,”name”:”rose”,”candidateUserId”:null,”gender”:”Female”,”philosophy”:”Php”,”voteCount”:”1″,}
]

Insert from Json Variable into var d = new Date();

I have some code that displays the weather and items from OpenWeatherMap.

Two of the Json fields are sunrise & sunset which display a UnixTimeStamp.

I’m trying to convert to HumanTimeStamp within my code but I’m lost.

Here is some of my code:

<div id="sunrise"></div>
  <div id="cityName"></div>
  <img src=""id="icon">
  <div id="temp"></div>
  <div id="description"></div>

var d = new Date();
var n = d.toLocaleDateString();
document.getElementById("date").innerHTML = d;




function drawWeather( d ) {
  var celcius = Math.round(parseFloat(d.main.temp)-273.15);
  var fahrenheit = Math.round(((parseFloat(d.main.temp)-273.15)*1.8)+32);
  document.getElementById('sunrise').innerHTML = d.sys.sunrise;

  document.getElementById('cityName').innerHTML = d.name;
  document.getElementById('description').innerHTML = d.weather[0].description;
  document.getElementById('temp').innerHTML = fahrenheit + '&deg;';
  document.getElementById('icon').src = `http://openweathermap.org/img/w/${d.weather[0].icon}.png`;
 }