Failed to Assign Value to InputElement using Puppeteer

I am trying to set a value to an Input/TextArea element in html using puppeteer without success. The code is transpiled with typescript.

Here I use YouTube as an example.

First it should navigate to youtube, then select the input box with pseudo-class css selector, and set the value according to the variables: prefix and caption.

The script shuts down as soon as it starts to perform page.eval. I am not sure if I am using the wrong css selector. There might be an issue when I am try to assign string to “value” property as well.

(async ()=>{
const searchbox='html>body>ytd-app>div>div>ytd-masthead>div:nth-of-type(3)/div:nth-of-type(2)/ytd-searchbox/form/div:first-of-type/div:first-of-type/input'
const puppeteer  = require("puppeteer")
const browser = await puppeteer.launch({headless:false, defaultViewport: null, slowMo: 100});
const page = await browser.newPage();

    await page.goto('https://www.youtube.com/');
    await uploadPhoto("Some", " Video");
    async function uploadPhoto(prefix:string, caption:string) {
        await page.evaluate( (searchbox:string, prefix:string, caption:string) => {
            (document.querySelector(searchbox) as HTMLInputElement).value = `${prefix} ${caption}`},
            searchbox, prefix, caption)
    }
    console.log("finish")
})();

Webpack Code Splitting Changes Entry Point?

I have been optimizing front-end code and page load speeds on an app. I have run into some issues after I began doing code splitting in Webpack.

After I included the following line in the config, the styles and scripts had stopped loading

optimization: {
    minimize: IS_PRODUCTION,
    splitChunks: {
    chunks: 'all',
    },
},

When I do not chunk the code, the chunks look like this

enter image description here

After I chunk the code, the chunks are as follows

enter image description here

That is, it appears to me that somehow 789.js takes place of index.js. However, in the template, I am including the file as

<script src="{% static 'index.js' %}" type="text/javascript" defer></script>

My question is why this happens, and what should be done to fix it? Chunking seems profitable here since there are three instances of jQuery and probably other things.

Test primitive value on if statement with Jest

I would like to create a test with Jest to make sure there is an if statement in my code. Let’s say we have a function that receives a string and I need to verify if this string includes something in it, if there is execute another function otherwise just ignore it.

function create (str) {
  if (str.includes('something')) {
    otherFunction()
  }

  ...
}

So I want not just to make sure there is an if statement, I also want that the string “calling” includes is str. I know I can use String.prototype but it does not make sure the string “calling” includes is str, any other string calling the same function passes the test

What I have till now:

test('Should call otherFunction if str includes something', () => {
  const { sut, otherObj } = makeSut()
  const otherFunctionSpy = jest.spyOn(otherObj, 'otherFunction')
  const includesSpy = jest.spyOn(String.prototype, 'includes')

  sut.create('has_something')

  expect(includesSpy).toHaveBeenCalledWith('something')
  expect(otherFunctionSpy).toHaveBeenCalled()
})

when passing array.length to a function in reactjs it gives undefined

const App = () => {
  const anecdotes = [
    'If it hurts, do it more often',
    'Adding manpower to a late software project makes it later!',
    'The first 90 percent of the code accounts for the first 10 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.',
    'Any fool can write code that a computer can understand. Good programmers write code that humans can understand.',
    'Premature optimization is the root of all evil.',
    'Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.',
    'Programming without an extremely heavy use of console.log is same as if a doctor would refuse to use x-rays or blood tests when diagnosing patients'
  ]
  const [selected, setSelected] = useState(0)
  const len = anecdotes.length
  console.log(len)
  const handleClick = () => {
    console.log(Math.floor(Math.random() * (anecdotes.length)))
    const index = GetRandomInt(len) // Math.floor(Math.random() * (anecdotes.length))
    while (index === selected) {
      index = GetRandomInt(len) // Math.floor(Math.random() * (anecdotes.length))
    }
    setSelected(index)
  }
  return (
    <div>
      <h1>Anecdote of the day</h1>
      <Display text={anecdotes[selected]} />
      <Button handleClick={handleClick} text={'Next anecdote'} />
      {/* {anecdotes[selected]} */}
    </div>
  )
}

The above code prints three values to the console

  1. assigned variable that contains array length
  2. Direct usage of array length to create a random integer
  3. Passed value to function to achieve the same in step 2 using function

Can someone tell me why this is happening? Am I passing the value incorrectly either datatype mismatch or something? I am a newbie in reactjs and learning through a course and this is one of the exercises where I am stuck.

How to make text/div appear when the user stops scrolling

I’m trying to achieve an effect where the javascript detects whether the user has stopped scrolling/hovering over the page, and slowly shows a piece of text over the page, sort of like a paywall. The effect I’m trying to achieve is a simplified version of this website where when the user is inactive for a certain amount of time, eyes start to appear on the page

What’s the difference between `() => { func() }` and `func` when used as param to `promise.catch()`?

var p = new Promise((res, rej) => {
    // reject after 1 second
    setTimeout(() => {
        rej(123)
    }, 1000)
})

p.catch(() => { location.reload() }) // works fine

The code works fine, but since location.reload is a function, no need to wrap it again with a lambda, so it’s changed to:

var p = new Promise((res, rej) => {
    // reject after 1 second
    setTimeout(() => {
        rej(123)
    }, 1000)
})

p.catch(location.reload) // not work

It doesn’t work, there is an exception and not caught by the p.catch(), why is that ?

Best way to filter array in nested array

I need to find a better way to implement an extraction of an array from a bigger array and filter that sub-array into a new one, I want to avoid using for loop into another for loop here’s my code:

async function getOrdersList() {
  try {
    let url = `MY_URL`;
    
    let data = await fetch(url);
    let res =  await data.json();
    if(!res) throw new Error({'error':'no response'});
    
    let orders = res.orders;
    let lineItems = [];
    let lineItem = {};
    
    for (const [i, value] of orders.entries()) {
        let inlineItems = value.line_items;
        for (const [j, value2] of inlineItems.entries()) {
            lineItem['id'] = value2.shopify_product_id;
          lineItem['qty'] = value2.quantity;
          lineItems.push(lineItem)
        }
    }
    
    return lineItems;
  }
  catch(error) {
        console.error(error);
      } 
}

How to remove words from values start with an specific word exp @specificword

I have images which have an attribute aria-label with values. As example

aria-label="And just like that we wake up and it appears we live by the ocean... ;)
@ReverieRetreat #Reverieretreat #Retreatcenter #Reverie #SierraFoothills
#Eldoradocounty #infinitypool
#ElDoradoCountyCa #VisitEldoradocounty @visiteldorado #VisitEldorado #VisitGoldcountry #Goldcountry #California
#VisitCalifornia @VisitCalifornia #applehill @applehillofficial 
#tasteintravel #adventureseeker #lovetravel #travelnow @natgeotravel #natgeotravel
#local #sacramento #natgeotravel"

Here I want to remove words starting with @ and # also remove words from the first word here which is @ReverieRetreat

Please someone help me how can I do that.

XHR request response is an HTML object. How can I keep it and display it the way it is?

I have a server-side xQuery which transforms an XML file into an HTML document. I want to send a request behind the scenes to that xQuery, get the HTML back, and inject it in my page, obviously retaining all the structure as it is without parsing it or traversing the nodes again.

        function loadXSLtoHTML () {
             document.getElementById('xslt-transformation').innerHTML = this.respinseXML
           }
           
           var oReq = new XMLHttpRequest();
           oReq.addEventListener("load", loadXSLtoHTML);
           
           oReq.open("GET", "xquery generating HTML");
           oReq.responseType = "document";
           oReq.send();

I know about the limitations of XHR calls. Is there really not a way of keeping my response HTML and injecting it as it is?

How can I create an triangle shape using css on the right side of the list group of bootstrap?

enter image description here

Hey Guys!! So I want to create a triangle shape using css at the end of the list item.
I have used list group component of bootstrap to display the list
Below I have added the snippet of my code.
I have also mentioned the desired output image
I only just want to know how can I add that triangle on the right side.

   
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Assigment 6 Part2</title>
   <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
   <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="assignment6.css">
    <script src="
    https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
        </script>
        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <link href="https://fonts.googleapis.com/css2?family=Mulish:wght@200&display=swap" rel="stylesheet">
</head>
<body>
   
    <div class="row">
        <div class="col-4 col-md-4 col-lg-5">
            <ul class="list-group list-group-flush" id="list-tab" role="tablist">
                <li class="list-group-item text-lg-end active" id="list-home-list"  role="tab" data-bs-toggle="list" href="#list-home" aria-controls="list-home"><i class="fas fa-couch"></i>&nbsp;&nbsp;&nbsp;Master Bedrooms</li>
                <li class="list-group-item text-lg-end  " id="list-profile-list"  role="tab" data-bs-toggle="list" href="#list-profile"><i class="fas fa-utensils"></i>&nbsp;&nbsp;&nbsp;Breakfast Buffet</li>
                <li class="list-group-item text-lg-end " id="list-home-list"  role="tab" data-bs-toggle="list" href="#list-messages">Fitness Center</li>
                <li class="list-group-item text-lg-end " id="list-home-list"  role="tab" data-bs-toggle="list" href="#list-settings">24 hours Reception</li>
                <li class="list-group-item text-lg-end " role="tab" id="list-home-list" data-bs-toggle="list" href="#list-home">Pool & Spa </li>
                <li class="list-group-item text-lg-end " role="tab" id="list-home-list" data-bs-toggle="list" href="#list-home">Free Wifi</li>
                <li class="list-group-item text-lg-end " role="tab" id="list-home-list" data-bs-toggle="list" href="#list-home">Resto bar</li>
              </ul>
        </div>
        <div class="col-8 col-md-6 col-lg-6">
          <div class="tab-content" id="nav-tabContent">
            <div class="tab-pane fade show active" id="list-home" role="tabpanel" aria-labelledby="list-home-list">
                <h2>Master Bedrooms</h2>
                <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nesciunt voluptate, quibusdam sunt iste dolores consequatur</p>
                <p>Inventore fugit error iure nisi reiciendis fugiat illo pariatur quam sequi quod iusto facilis officiis nobis sit quis molestias asperiores rem, blanditiis! Commodi exercitationem vitae deserunt qui nihil ea, tempore et quam natus quaerat doloremque.
                </p>
            </div>
            <div class="tab-pane fade" id="list-profile" role="tabpanel" aria-labelledby="list-profile-list">h2</div>
            <div class="tab-pane fade" id="list-messages" role="tabpanel" aria-labelledby="list-messages-list">h3</div>
            <div class="tab-pane fade" id="list-settings" role="tabpanel" aria-labelledby="list-settings-list">h4</div>
          </div>
        </div>
      </div>
 

Dynamic routes in react router v6

Please how do I match the coinId in this code, I’m using react router version 6, and it’s not delivering.

<Routes>
  <Route path='/crypto/:coinId element={<Crypto details />} />
</Routes>

Please I’d really appreciate your help, the code above is from version 5

React Native and React Native Web- document is not defined error

I am trying to create a currency converter app. I am trying to create 2 dropdowns for selecting currencies. During that, I figured out that the library I am using, “react native material dropdown”, does not work on web. This is the Error that I am getting with react native material dropdown on web:
screenshot of error

So, I added react native web to my app and used the docs to add the following 2 lines of code to the react native app:

AppRegistry.registerComponent('App', () => App);
AppRegistry.runApplication('App', {rootTag: document.getElementById('react-root')});

This is my entire “App.js”:

import React from 'react';
import {
  View,
  StyleSheet,
  TextInput,
  Text,
  TouchableOpacity,
  AppRegistry
} from 'react-native';
import { Header } from 'react-native-elements';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import {Dropdown} from 'react-native-material-dropdown';

export default class App extends React.Component {
  constructor() {
    super();
  }

  render() {
    return (
      <SafeAreaProvider>
        <View style={styles.appContainer}>
          <Header
            backgroundColor={'#2CC779'}
            centerComponent={{
              text: 'Currency Converter',
              style: {
                color: '#fff',
                fontSize: 20,
              },
            }}
          />
          <Text style={{ marginTop: 20 }}>Enter currency to convert from:</Text>


          <Text style={{ marginTop: 50 }}>Enter currency to convert to:</Text>
          

          
        </View>
      </SafeAreaProvider>
    );
  }
}

const styles = StyleSheet.create({
  appContainer: {
    flex: 1,
    backgroundColor: '#18C6C9',
  },
  currencyInput: {
    marginTop: 50,
    width: '80%',
    alignSelf: 'center',
    height: 40,
    textAlign: 'center',
    borderWidth: 4,
    outline: 'none',
  },
  convertButton: {
    width: '50%',
    height: 55,
    alignSelf: 'center',
    padding: 10,
    margin: 100,
  },
  convertButtonText: {
    textAlign: 'center',
    fontSize: 30,
    fontWeight: 'bold',
  },
});

AppRegistry.registerComponent('App', () => App);
AppRegistry.runApplication('App', {rootTag: document.getElementById('react-root')});

This is my “package.json”:

{
  "dependencies": {
    "expo-constants": "~12.1.3",
    "@expo/vector-icons": "^12.0.0",
    "react-native-paper": "4.9.2",
    "react-native-elements": "*",
    "react-native-safe-area-context": "3.3.2",
    "react-native-material-dropdown": "*"
  }
}

But now, after that, expo is saying that “document is not defined”: screenshot of second error

What do I do next and how should I proceed?
(P.S. Keep in mind that this is inside an online Expo environment in the Snack editor)

why styles don’t apply on dangerouslySetInnerHTML

i need to render some styled jsx tags in my component by using useTranslation hook and dangerouslySetInnerHTML, those tags are stored in a json file , i found that dangerouslySetInnerHTML work’s fine but don’t apply tailwind styles for each tag,

json file:

{
   "about-text":"<div className='text-blue px-5'><p>Text ...</p</div>",
}

inside componenets:

<div className="p-10">
<div
   dangerouslySetInnerHTML={{
      __html: t('about-text'),
    }}
   />
</div>

How to modify the JavaScript code so that it works on the new structure of links?

  // Start Current Link (ACTIVE MENU LINK)
  jQuery(document).ready(function () {
    jQuery(".navigation > li").click(function () {
      jQuery(".navigation > li").removeClass("current");
      jQuery(this).addClass("current");
    });
    var loc = window.location.href;
    jQuery(".navigation > li").removeClass("current");
    jQuery(".navigation > li > a").each(function () {
      if (loc.indexOf(jQuery(this).attr("href")) != -1) {
        jQuery(this).closest("li").addClass("current");
      }
    });
    // The Below Code for fix current active dropdown when choose sub link from the dropdown menu
    jQuery(".navigation > .dropdown").click(function () {
      jQuery(".navigation > .dropdown").removeClass("current");
      jQuery(this).addClass("current");
    });
    var loc = window.location.href;
    jQuery(".navigation > .dropdown > ul > li").removeClass("current");
    jQuery(".navigation > .dropdown > ul > li > a").each(function () {
      if (loc.indexOf(jQuery(this).attr("href")) != -1) {
        jQuery(this).closest(".dropdown").addClass("current");
      }
    });
  });
ul {
  list-style: none;
}
a {
  text-decoration: none;
}
.main-menu .navigation {
  display: flex;
  align-items: center;
  position: relative;
}
.main-menu .navigation > li {
  padding: 39.5px 0;
  margin: 0 15px;
  z-index: 2;
  -webkit-transition: all 500ms ease;
  -moz-transition: all 500ms ease;
  -ms-transition: all 500ms ease;
  -o-transition: all 500ms ease;
  transition: all 500ms ease;
}
.main-menu .navigation > li.current > a {
  color: #da2c46;
}
.main-menu .navigation > li.current > a::before {
  -webkit-transform: scale(1, 1);
  -moz-transform: scale(1, 1);
  -ms-transform: scale(1, 1);
  -o-transform: scale(1, 1);
  transform: scale(1, 1);
}
.main-menu .navigation > li:first-child {
  margin-left: 0;
}
.main-menu .navigation > li:last-child {
  margin-right: 0;
}
.main-menu .navigation > li > a {
  color: #222222;
  /* color: #ffffff; */
  position: relative;
  display: flex;
  font-weight: 600;
  opacity: 1;
  z-index: 1;
  -webkit-transition: all 500ms ease;
  -moz-transition: all 500ms ease;
  -ms-transition: all 500ms ease;
  -o-transition: all 500ms ease;
  transition: all 500ms ease;
}
.main-menu .navigation > li > a::before {
  content: "";
  position: absolute;
  width: 100%;
  height: 1px;
  background-color: #da2c46;
  bottom: -3px;
  left: 0;
  -webkit-transform: scale(0, 0);
  -moz-transform: scale(0, 0);
  -ms-transform: scale(0, 0);
  -o-transform: scale(0, 0);
  transform: scale(0, 0);
  -webkit-transition: all 500ms ease;
  -moz-transition: all 500ms ease;
  -ms-transition: all 500ms ease;
  -o-transition: all 500ms ease;
  transition: all 500ms ease;
}
.main-menu .navigation > li > a::after {
  content: "";
  position: absolute;
}
.main-menu .navigation > li > a:hover {
  color: #da2c46;
}
.main-menu .navigation > li > a:hover::before {
  -webkit-transform: scale(1, 1);
  -moz-transform: scale(1, 1);
  -ms-transform: scale(1, 1);
  -o-transform: scale(1, 1);
  transform: scale(1, 1);
}
.main-menu .navigation > li > ul {
  position: absolute;
  left: inherit;
  top: 100%;
  width: 250px;
  z-index: 100;
  display: none;
  opacity: 0;
  visibility: hidden;
  background-color: #ffffff;
  -webkit-transform: translateY(30px);
  -moz-transform: translateY(30px);
  -ms-transform: translateY(30px);
  -o-transform: translateY(30px);
  transform: translateY(30px);
  -webkit-box-shadow: 2px 2px 5px 1px rgba(0, 0, 0, 0.05),
    -2px 0px 5px 1px rgba(0, 0, 0, 0.05);
  -moz-box-shadow: 2px 2px 5px 1px rgba(0, 0, 0, 0.05),
    -2px 0px 5px 1px rgba(0, 0, 0, 0.05);
  -ms-box-shadow: 2px 2px 5px 1px rgba(0, 0, 0, 0.05),
    -2px 0px 5px 1px rgba(0, 0, 0, 0.05);
  -o-box-shadow: 2px 2px 5px 1px rgba(0, 0, 0, 0.05),
    -2px 0px 5px 1px rgba(0, 0, 0, 0.05);
  box-shadow: 2px 2px 5px 1px rgba(0, 0, 0, 0.05),
    -2px 0px 5px 1px rgba(0, 0, 0, 0.05);
  -webkit-transform-origin: top;
  -moz-transform-origin: top;
  -ms-transform-origin: top;
  -o-transform-origin: top;
  transform-origin: top;
  -webkit-transition: all 2s ease-in-out;
  -moz-transition: all 2s ease-in-out;
  -ms-transition: all 2s ease-in-out;
  -o-transition: all 2s ease-in-out;
  transition: all 2s ease-in-out;
}
.main-menu .navigation > li > ul > li {
  position: relative;
  width: 100%;
  padding: 11px 30px;
  border-bottom: 1px solid #eeeeee;
}
.main-menu .navigation > li > ul > li > a {
  position: relative;
  display: block;
  padding: 6px 0px;
  line-height: 24px;
  text-transform: capitalize;
  color: #222222;
  text-align: left;
  transition: all 500ms ease;
  -webkit-transition: all 500ms ease;
  -moz-transition: all 500ms ease;
  -ms-transition: all 500ms ease;
  -o-transition: all 500ms ease;
}
.main-menu .navigation > li > ul > li > a:hover {
  color: #da2c46;
}
.main-menu .navigation > li.dropdown:hover > ul {
  display: block;
  visibility: visible;
  opacity: 1;
  -webkit-transform: translateY(0);
  -moz-transform: translateY(0);
  -ms-transform: translateY(0);
  -o-transform: translateY(0);
  transform: translateY(0);
  -webkit-transition: all 2s ease-in-out;
  -moz-transition: all 2s ease-in-out;
  -ms-transition: all 2s ease-in-out;
  -o-transition: all 2s ease-in-out;
  transition: all 2s ease-in-out;
}
.main-menu .navigation > li.dropdown .dropdown-btn {
  position: absolute;
  right: -32px;
  top: 66px;
  width: 34px;
  height: 30px;
  text-align: center;
  font-size: 18px;
  line-height: 26px;
  color: #3b3b3b;
  cursor: pointer;
  display: none;
  z-index: 5;
  -webkit-transition: all 500ms ease;
  -moz-transition: all 500ms ease;
  -ms-transition: all 500ms ease;
  -o-transition: all 500ms ease;
  transition: all 500ms ease;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <nav class="main-menu navbar-expand-md me-auto navbar-light">
        <div class="collapse navbar-collapse show" id="navbarSupportedContent">
            <ul class="navigation">
                <li><a href="/">Home</a></li>
                <li><a href="/about-us.html">About</a></li>
                <li class="dropdown"><a href="/services.html">Services</a>
                    <ul>
                        <li><a href="/finance-consulting.html">Finance
                                Consulting</a>
                        </li>
                        <li><a href="/tax-management.html">Tax Management</a></li>
                        <li><a href="/economic-planning.html">Economic Planning</a></li>
                        <li><a href="/strategy-thinking.html">Strategy Thinking</a></li>
                        <li><a href="/market-analysis.html">Market Analysis</a></li>
                        <li><a href="/content-optimize.html">Content Optimize</a></li>
                    </ul>
                </li>
                <li><a href="/pricing.html">pricing</a></li>
                <li class="dropdown"><a href="/blog.html">Blog</a>
                    <ul>
                        <li><a href="/blog-details.html">Blog details</a></li>
                        <li><a href="/404.html">Error 404 Page</a></li>
                        <li><a href="/privacy-policy.html">Privacy Policy</a></li>
                    </ul>
                </li>
                <li><a href="/contact.html">Contact</a></li>
            </ul>
        </div>
    </nav>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
   
</body>

</html>

Hello
I got this javascript code by searching (its function is to add and remove active class to ‘li’ class for the open page) and it executed as is.
Now, I am working on an html site and the link was “localhost/index.html”
And the code was working good on this format
and because I want to remove the “index.html” link so that it shows the main without adding index.html, I switched home link from “index.html” to “/” and added “/” before each page link as shown in the html structure, and the result was that the class “current” stayed on the home link and also added to the open page, meaning when you open about us page for example you will find the css effects of the class “current” is enabled on it and on the home page link
I tried to modify the javascript code so that the job works on the new link, which is local only, without adding /index.html, but I don’t know
I hope you will help me and tell me how to write the code so that it achieves the functions required of it
With thanks