Require Puppeteer in Electron Preload file

I am trying to require the puppeteer module in my preload.js file to be able to provide it to my render.js. I am able to require it but at the time when I pass it to the exposeInMainWorld function it seems to be not complete.

const puppeteer = require('puppeteer')
const dappeteer = require('@chainsafe/dappeteer')


console.log(puppeteer)
console.log(JSON.parse(JSON.stringify(puppeteer)))


contextBridge.exposeInMainWorld('electronAPI', {
    puppeteer
})

this code shows the following logs:
logs

this behavior iseems to be unique to this module.

is it possible to define an variable as base url on nuxt.js

what i trying to do is define a base url variable for my api which is able to be called everywhere on nuxt app. for example im trying to call an image from my api storage like bellow

<img :src="`${baseUrl}/****/****.png`">

asuming i can define the variable,so i dont need to change every img url when the api domain changed. or I would be very thankful for introduce any better way to calling image from api storage. btw im using laravel as the api.

Is there any way to resolve the CORS error that occurs when using html2canvas to retrieve a custom leaflet in AWS s3?

I have a question about the application of html2canvas in a custom leaflet deployed to AWS s3.

I have created a custom TileLayer in a leaflet and deployed the data to AWS s3 so that it can be retrieved with the following URL as an example.

http://{s}.somedomain.com/{z}/{x}/{y}.png

In this state, we have succeeded in drawing the map data using react-leaflet.

However, when we try to get the map data image using html2canvas, the map data will not be displayed.
In this case, the following error message is output to the console.

Access to image at 'http://{s}.somedomain.com/{z}/{x}/{y}.png' from origin 'http://localhost:3000/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

It looks like a CORS error, but the configuration in AWS S3 is as follows.

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET".
        ],
        "AllowedOrigins": [
            "*"
        ],
        "ExposeHeaders": []
    }
]

As you can see, we are allowing requests from all origins.
However, I can’t figure out why the above error occurs.

If anyone has encountered such a situation, please let me know the solution.

How to get this function to change style sheets

I am new to jS and trying some simple tasks but even these so-called simple tasks are proving difficult at times. Please help me understand why this doesn’t work. This snippet is to change style sheets by using a toggle. As you can probably work out.

I have two style sheets, a toggle (checkbox) and a function with an if else statement. Why can I not get this to work? Thank you

function toggleTheme() {

  let theme = document.getElementsByTagName('link')[0];

  if (theme.getAttribute('href') == 'darkstyle.css') {
    theme.setAttribute('href', 'lightstyle.css');
  } else {
    theme.setAttribute('href', 'darkstyle.css');
  }
}
<link rel="stylesheet" href="darkstyle.css" />

<link rel="stylesheet" href="lightstyle.css" />

<label class="switch">
  <input  type="checkbox" />
  <span onchange="toggleTheme()" class="slider round"></span>
</label>

How to animate sorted table rows

I have a table with <tbody id="tbody"></tbody>

Every 10sec, I send an xhr request to a microcontroller that returns a json formatted response with scanned wifi networks sorted by signal strength :

[...]

    function scanWLAN() {
      let scanRequest = new XMLHttpRequest();
      scanRequest.open("GET", scanUrl);
      scanRequest.responseType = "json";
      scanRequest.send();
      scanRequest.onload = function() {
        loading_el.remove();
        var list = sortByKey(scanRequest.response, "RSSI");
        if (list.length) {
          addRow(list);
        }
      }
    }

    function addRow(list) {
      tbody_el.innerHTML = "";

      for (var i = 0; i < list.length; i++) {
        let newRow = document.createElement('tr');

        let newColSSID = document.createElement('td');
        let newColRSSI = document.createElement('td');
        /*let newColEncryptionType = document.createElement('td');
        let newColBSSID = document.createElement('td');
        let newColChannel = document.createElement('td');
        let newColIsHidden = document.createElement('td');*/

        let SSID = list[i].SSID;
        let RSSI = list[i].RSSI;
        let encryptionType = list[i].encryptionType;
        let BSSID = list[i].BSSID;
        let channel = list[i].channel;
        let isHidden = list[i].isHidden;

        if (SSID == WLAN_SSID) {
          newRow.classList.add("table-success");
        }
        newColSSID.innerHTML = '<span class="cursor-pointer" onclick="autocompleteSSID('' + SSID + '')">' + SSID + '</span>';
        //newColRSSI.textContent = RSSI;
        newColRSSI.innerHTML = '<span title="' + RSSI + ' dBm">' + icons["reception-" + getSignalLevel(RSSI)] + '</span';
        /*newColEncryptionType.textContent = encryptionType;
        newColBSSID.textContent = BSSID;
        newColChannel.textContent = channel;
        newColIsHidden.textContent = isHidden;*/

        newRow.appendChild(newColSSID);
        newRow.appendChild(newColRSSI);
        /*newRow.appendChild(newColEncryptionType);
        newRow.appendChild(newColBSSID);
        newRow.appendChild(newColChannel);
        newRow.appendChild(newColIsHidden);*/

        tbody_el.appendChild(newRow);
      }
    }

[...]

    scanWLAN();
    setInterval(function () {
      scanWLAN();
    }, 11000);

[...]

This refreshes the table rows quite abruptly. I would like to make it look cooler with transitions/ animations when a newly discovered network gets inserted in between existing rows, or when a network sends better signal and is moved up the list.

How can I achieve this with pure javascript or css?

Please note than I can not embed heavy libraries/plugins such a jQuery as all files/codes must be hosted on a chip with very low memory.

What would be the appropriate keywords to find docs about what I am trying to achieve?

Drag and drop file upload submitting immediately

I’m following this tutorial to try to figure out how to build a drag-and-drop file upload box. I can’t use jQuery. The problem is that when I release a file over the box, the form automatically submits to the target specified in the form action property despite my trying to override it. Any ideas? I have copied out the upload box –

<form id="uploader" class="box" method="post" action="" enctype="multipart/form-data">               
  <div class="box__input">                                                                           
      <svg class="box__icon" xmlns="http://www.w3.org/2000/svg" width="50" height="43" viewBox="0 0 50 43"><path d="M48.4 26.5c-.9 0-1.7.7-1.7 1.7v11.6h-43.3v-11.6c0-.9-.7-1.7-1.7-1.7s-1.7.7-1.7 1.7v13.2c0 .9.7 1.7 1.7 1.7h46.7c.9 0 1.7-.7 1.7-1.7v-13.2c0-1-.7-1.7-1.7-1.7zm-24.5 6.1c.3.3.8.5 1.2.5.4 0 .9-.2 1.2-.5l10-11.6c.7-.7.7-1.7 0-2.4s-1.7-.7-2.4 0l-7.1 8.3v-25.3c0-.9-.7-1.7-1.7-1.7s-1.7.7-1.7 1.7v25.3l-7.1-8.3c-.7-.7-1.7-.7-2.4 0s-.7 1.7 0 2.4l10 11.6z"></path></svg>                                                    
      <br>                                                                                           
      <input class="box__file" type="file" name="files[]" id="file" data-multiple-caption="{count} file selected" multiple />
    <label class="file-label" for="file"><strong>Choose a file</strong><span class="box__dragndrop"> or drag it here</span>.</label>
  </div>                                                                                             
  <div class="box__uploading">Uploading…</div>                                                       
  <div class="box__success">Done!</div>                                                              
  <div class="box__error">Error! <span></span>.</div>                                                
    <button class="box__button" type="button">Upload</button>                                        
</form>

and I have the following in javascript below it:

var isAdvancedUpload = function() {                                                                  
  var div = document.createElement('div');                                                           
  return (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div)) && 'FormData' in window && 'FileReader' in window;
}();                                                                                                 
                                                                                                     
var form = document.querySelector('.box');                                                           
                                                                                                     
if (isAdvancedUpload) {                                                                              
  form.className += " " + 'has-advanced-upload';                                                     
}                                                                                                    
                                                                                                     
if (isAdvancedUpload) {                                                                              
                                                                                                     
  var droppedFiles = false;                                                                          
                                                                                                     
  'drag dragstart dragend dragover dragenter dragleave drop'.split(" ").forEach(function(e) {        
      window.addEventListener(e, function(f){                                                        
          f.preventDefault();                                                                        
          f.stopPropagation();                                                                       
      }, false);                                                                                     
  });                                                                                                
                                                                                                     
  window.addEventListener('dragover',                                                                
      ()=>form.classList.add('is-dragover'),                                                         
    false                                                                                            
  );                                                                                                 
                         
  window.addEventListener('dragenter',                                                               
      ()=>form.classList.add('is-dragover'),                                                         
    false                                                                                            
  );                                                                                                 
  window.addEventListener('dragleave',                                                               
      ()=>form.classList.remove('is-dragover'),                                                      
    false                                                                                            
  );                                                                                                 
  window.addEventListener('dragend',                                                                 
      ()=>form.classList.remove('is-dragover'),                                                      
    false                                                                                            
  );                                                                                                 
  window.addEventListener('dragdrop',                                                                
      ()=>form.classList.remove('is-dragover'),                                                      
    false                                                                                            
  );                                                                                                 
  window.addEventListener('drop',                                                                    
      (e)=>{                                                                                         
        droppedFiles = e.dataTransfer.files;                                                         
        console.log(droppedFiles);                                                                   
        form.submit();                                                                               
      },                                                                                             
    false                                                                                            
  );                                                                                                 
  form.addEventListener('submit', function(e) {                                                      
      form = document.querySelector("#uploader");                                                    
      if ('is-uploading' in form.classList) return false;                                            
      form.classList.add('is-uploading');                                                            
      form.classList.remove('is-error');                                                             
      input = document.querySelector('input[type="file"]');                                          
                                                                                                     
      /* code here to collect the input, package it as a FormData, and fetch it to a specific POST endpoint */

Running two browser instances in parallel for same list of websites in Puppeteer

I wrote javascript code for a web crawler that scraps data from a list of websites (in csv file) in a single browser instance (code below). Now I want to modify the code for the scenario in which every single website in the list runs parallel at the same time in two browser instances. For example, a website www.a.com in the list should run in parallel at the same time on two browser instances and the same goes for the rest of the websites. If anyone can help me, please. I would be very thankful.

(async () => {

require("dotenv").config();
if (!process.env.PROXY_SPKI_FINGERPRINT) {
    throw new Error("PROXY_SPKI_FINGERPRINT is not defined in environment.");
}

const fs = require("fs");
const fsPromises = fs.promises;
const pptr = require("puppeteer");

const browser = await pptr.launch({
    args: [
        "--proxy-server=https://127.0.0.1:8000",
        "--ignore-certificate-errors-spki-list=" + process.env.PROXY_SPKI_FINGERPRINT,
        "--disable-web-security",
    ],
    // headless: false,
});

const sites = (await fsPromises.readFile(process.argv[2])) // sites list in csv file
    .toString()
    .split("n")
    .map(line => line.split(",")[1])
    .filter(s => s);

for (let i in sites) {
    const site = sites[i];
    console.log(`[${i}] ${site}`);
    try {
        await fsPromises.appendFile("data.txt", JSON.stringify(await crawl(browser, site)) + "n");
    } catch (e) {
        console.error(e);
    }
}

await browser.close();

async function crawl(browser, site) {
    const page = await browser.newPage();

    try {
        const grepResult = [];

        page.on("request", async request => {
            request.continue();
        })

        page.on("response", async response => {
            try {
                if (response.request().resourceType() === "script" &&
                    response.headers()["content-type"] &&
                    response.headers()["content-type"].includes("javascript")) {
                        const js = await response.text();
                        const grepPartResult = grepMagicWords(js);
                        grepResult.push([response.request().url(), grepPartResult]);
                }
            } catch (e) {}
        });

        await page.setRequestInterception(true);

        try {
            await page.goto("http://" + site, {waitUntil: "load", timeout: 60000});
            await new Promise(resolve => { setTimeout(resolve, 10000); });
        } catch (e) { console.error(e); }

        const [flows, url] = await Promise.race([
            page.evaluate(() => [J$.FLOWS, document.URL]),
            new Promise((_, reject) => { setTimeout(() => { reject(); }, 5000); })
        ]);

        return {url: url, grepResult: grepResult, flows: flows};
    } finally {
        await page.close();
    }

    function grepMagicWords(js) {
        var re = /(?:'|")(?:g|s)etItem(?:'|")/g, match, result = [];
        while (match = re.exec(js)) {
            result.push(js.substring(match.index - 100, match.index + 100));
        }
        return result;
    }
}

})();

How to apply conditional routing in Angular where the condition is to make sure that the previous page has been visited?

I have an Angular web app where to sign up you go through different pages:

  1. Fill in your name and email
  2. Fill in your password
  3. Fill in your confirmation code

Hence the URL changes from website.com/intake to website.com/intake/signup to website.com/intake/confirmation.

My problem is that it is currently possible for a user to change the url from website.com/intake to website.com/intake/signup and finish the registration without filling the other information. I would like to prevent that but I am not sure how to use routing in this case.

I want to make sure that the user can go to the next page only if he has been to the first one and has filled in. Now I know, if I make the form fields * required it will not allow the user to go further but he will still be able to bypass that by changing the url.

How do I solve that?

How to Webscrap item name database loaded from website using nodejs ‘cheerio’ and ‘request-promise’

I am trying to get guild names from the loaded items in a particular url, but the output results are far from the expected. What am I doing wrong?

Here is my code:

const request = require('request-promise');
const cheerio = require('cheerio');
const url = 'https://us.tamrieltradecentre.com/pc/Trade/SearchResult?SearchType=Sell&ItemID=11807&ItemNamePattern=Aetherial+Dust&PriceMax=450000';
const time_out = 3000; //300000 // 5 minutes

(async () => {
    let data = [];
    const response = await request({
        uri: url,
        headers: {
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
            "accept-encoding": "gzip, deflate, br",
            "accept-language": "pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7,ja;q=0.6",
        },
        gzip: true,
    });

    let $ = cheerio.load(response);
    let guild = $('div[data-bind="text: GuildName"]')[0]

    data.push({
        lastGuild: guild,
    });

    console.log(data)

})();

expected output
code output

My code is saying there are syntax errors where i am unable to find them… can someone help me please?

it is saying line 3 mainly. I really am confused, seeing as im a beginer that is expected, but i could really use some help because this is for my schools coding team, and I will get yelled at >:(

   <html>
     <head>
         <title>Javascript Stuff</title>
       </head>  

   <body>
    
   <script>
var input=prompt("Enter a number:");
if input> 0 {
    alert("negative")
}
else (input < 0)
   alert("Zero");
if else{ 
   alert("Positive");
}
    </script>
    </body>
                
                </html>

Shadowroot : Attaching jquery event handlers to multiple elements under shadowRoot

So I’m using a jQuery plugin under shadowRoot in my app. The HTML is as follows

#shadow-root
<div id="container">
   <div class="display-item">Item 1</div>
   <div class="display-item">Item 2</div>
   <div class="display-item">Item 3</div>
   <div class="display-item">Item 4</div>
</div>

I want to attach event listeners to the divs with class = “display-item” for events like mousedown,mousedown,focus. I tried the following:

let root = document.getElementById(divID).shadowRoot;
$(root).on('mousedown', '#container div.display-item', function(event) {
//function 
});

But this doesn’t work. How could I make this work?

Javascript template literal strange behaviour

Why is the following code syntactically correct?

let v = ``(oldVal-newVal) / 1000;

It gives the following runtime error:

Uncaught TypeError: "" is not a function

My guess is the “ becomes a tagged template, and “” would be tag name, but not sure.
(I got to this by accidentally typing it instead of the Ctrl+` shortcut in VSCode. Took a day to find it. 😉

Pass data from Spring Boot app into javascript function

I am trying to pass latitude and longitude data from a MySQL database through my Spring Boot application into a javascript function. I was able to use Thymeleaf to display a table on the webpage with the data, so I know the service and controller classes are set up correctly.

Below shows how my table is populated:

<table style="word-wrap:break-word;white-space:normal;" class="table table-bordered">
    <thead class="table-dark">
        <tr>
            <th>Latitude</th>
            <th>Longitude</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        <th:block th:each="point : ${listPoints}">
            <tr>
                <td>[[${point.LAT}]]</td>
                <td>[[${point.LNG}]]</td>
            </tr>
        </th:block>
    </tbody>
</table>

I also hard coded the params of my javascript function which works. Below is the js function:

addMarker({lat:50.772775,lng:3.889969});

function addMarker(coords) {
    var marker = new google.maps.Marker({
        position: coords,
        map:map
    })
} 

I need a way to loop through my lat and lng’s to add a marker for each. Thank you!