Electron: Is it safe to expose ipcRenderer methods with only a startsWith if statement “protection”?

I have an electron application and I’m using contextBridge.exposeInMainWorld to expose some ipcRenderer methods such as .on , .removeListener and .invoke, these methods are “protected” by having an if statement that checks if the “channel” passed is valid.

Using the following code:


const validateIPC = (channel) => {
  if (!channel || !channel.startsWith("myapp:")) 
    return false;
 
  return true;
};

contextBridge.exposeInMainWorld("electron", {
ipcRenderer: {
    on(channel, listener) {
      if (validateIPC(channel)) {
        ipcRenderer.on(channel, (evt, message) => {
          listener(evt, message);
        });
      }
    },
    removeListener(channel, listener) {
      if (validateIPC(channel)) {
        ipcRenderer.removeListener(channel, (evt, message) => {
          listener(evt, message);
        });
      }
    },
    invoke(channel, data) {
      if (validateIPC(channel)) {
        return ipcRenderer.invoke(channel, data);
      }
    },
  },
};

Is it safe to only check if the channel starts with some random string? I saw this on the source code of vscode available on github, however I also read some solutions using an array of strings to validate the channels. If it is safe why can’t I just expose it without checking if the channel startsWith some random name? Are there any default channel that can’t be exposed?

how to set the value of Input from state

hope you’re doing well!
I am looking to set the value of Input from the state that i receive from props! I could set all the information from “profile” state in the placeholder but when putting it in the value field it doesn’t show anything
here’s my code :
the form i use :

                        <Form
                            name="basic"
                            wrapperCol={{ span: 24 }}
                            onFinish={onUpdate}
                            onFinishFailed={onFinishFailed}>
                            <FormItem>
                                <Input prefix={<ContactsTwoTone />} placeholder={profile.name} />
                            </FormItem>

                            <FormItem name="email"
                                rules={[
                                    {
                                        type: 'email',
                                        message: 'The input is not valid E-mail!',
                                    }
                                ]}
                            >
                                <Input value={profile.email} name="name" prefix={<MailTwoTone />} placeholder={profile}  />
                            </FormItem>
                            <FormItem name="mobile" value={profile.mobile} >
                                <Input value={profile.mobile} name="mobile" prefix={<PhoneTwoTone />} placeholder={profile.mobile} />
                            </FormItem>
                            <FormItem name="addres">
                                <Input name="addres" prefix={<HomeTwoTone />} placeholder={profile.addres} />
                            </FormItem>
                            <FormItem name="description">
                                <Input.TextArea name="description" placeholder="description" rows={4} prefix={<ContainerTwoTone />} />
                            </FormItem>
                            <FormItem>
                                <Button className="width-100" type="primary" htmlType="submit" onClick={onUpdate} >Update</Button>
                            </FormItem>


                        </Form> ``` 

the useEffect function and the declaration of state : 

const [visible, setVisible] = useState(false);
const FormItem = Form.Item;
const [profile, setProfile] = useState({});


useEffect(() => {
    setProfile(props.profile); 

},[props.profile] );
const showDrawer = () => {
    setVisible(true);
}; 

Invalid hook call. React js

Good afternoon. I’m trying to create my website using react. I’m rally new to react and js in general, so I have a problem. I wrote some registration logic, but it shows me that error:

Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

Here’s my code:

Register.jsx

import React from 'react';
import ReactDOM, {render} from "react-dom";
import '../../styles/Register.css';
import {Link} from "react-router-dom";
// import register from "./AuthMethods"
import Reg from "./AuthMethods";

function Register() {
    return (
        <div className="Register">
            <div id = "block_reg">
                <div id = "reg_top">Register</div>
                <input id = "nickname_input" placeholder="Nickname"/>
                <input id = "name_input" placeholder="Name"/>
                <input id = "surname_input" placeholder="Surname"/>
                <input id = "mail_input" placeholder="Email"/>
                <input type = "password" id = "password_input" placeholder="Password"/>
                <input type = "password" id = "password-repeat_input" placeholder="Repeat password"/>
                <button onClick={Reg} id = "reg_but"> Register</button>
                <div id = "alredy-has_div">Already have account?</div>
                <Link to="/" id = "already-has_but">Sign in!</Link>
            </div>
        </div>
    );
}

export default Register;

AuthMethods.jsx

import url from "../../configs"
import {Link, useNavigate} from "react-router-dom";

function Reg() {
    const navigate = useNavigate();
    var nickname = document.getElementById("nickname_input").value;
    var name = document.getElementById("name_input").value;
    var surname = document.getElementById("surname_input").value;
    var email = document.getElementById("mail_input").value;
    var password = document.getElementById("password_input").value;
    var repeatPassword = document.getElementById("nickname_input").value;
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "http://127.0.0.1:8000/api/register", false);
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.send(JSON.stringify({
        nickname: nickname,
        email: email,
        name: name,
        surname: surname,
        password: password
    }));

    if(xhr.status === 200) {
        navigate('/');
    } else if(xhr.status === 403) {
        alert("You cant use such nickname");
    } else {
        alert("Something went wrong");
    }

}

export default Reg;

If you know what can be the problem, please tell me. I’d really apreciate it!

how to compute array value and add extra file with sum of amount javascript

https://jsfiddle.net/dy6vhnsc/

expected like this

myData: [{
      id: 1,
      name: 'Russell',
      country: 'Windes',
      amount: 7,
      myaddedResult: [
        {
            id: 3,
            name: 'Watson',
            country: 'Australia',
            amount: 9,
            sumOfAmount: 16
          },
          {
            id: 4,
            name: 'Marcus',
            country: 'England',
            amount: 10,
            sumOfAmount: 17
          }
      ]
    },
    {
      id: 2,
      name: 'Smith',
      country: 'USA',
      amount: 8
    }
  ],
  ownerData: [{
      id: 3,
      name: 'Watson',
      country: 'Australia',
      amount: 9
    },
    {
      id: 4,
      name: 'Marcus',
      country: 'England',
      amount: 10
    }
  ]

how to add new field and add sum of amount into the new array in javascript what would be best option please guide

Thanks

How to reverse graph in CanvasJS

i have a code that should reverse the CanvasJS graph , But when i give reversed : true for x-axis nothing changes.

Can anybody help me with this

<?php
 
 $dataPoints1 = array(
     array("label"=> "2006", "y"=> 3289)
 );
  
 $dataPoints2 = array(
     array("label"=> "2006", "y"=> 1827)
 );
  
 $dataPoints3 = array(
     array("label"=> "2006", "y"=> 355)
 );
  
 $dataPoints4 = array(
     array("label"=> "2006", "y"=> 80)
 );
  
 $dataPoints5 = array(
     array("label"=> "2006", "y"=> 1)
 );
  
 $dataPoints6 = array(
     array("label"=> "2006", "y"=> 1108)
 );
  
 ?>
 <script>
 window.onload = function () {
  
 var chart = new CanvasJS.Chart("chartContainer", {
     theme: "light2",
     animationEnabled: true,
     toolTip:{
         shared: true,
         reversed: true
    },
    axisX:{
        gridThickness: 0,
        tickLength: 0,
        lineThickness: 0,
        labelFormatter: function(){
        return " ";
        },
        reversed:true
    },
    axisY:{
        gridThickness: 0,
        tickLength: 0,
        lineThickness: 0,
        labelFormatter: function(){
        return " ";
        },
        includeZero: true
    },
    legend: {
         cursor: "pointer",
         itemclick: toggleDataSeries
     },
     data: [
         {
             type: "stackedColumn",
             name: "Europe",
             showInLegend: true,
             yValueFormatString: "#,##0 MW",
             dataPoints: <?php echo json_encode($dataPoints1, JSON_NUMERIC_CHECK); ?>
         },{
             type: "stackedColumn",
             name: "Asia-Pacific",
             showInLegend: true,
             yValueFormatString: "#,##0 MW",
             dataPoints: <?php echo json_encode($dataPoints2, JSON_NUMERIC_CHECK); ?>
         },{
             type: "stackedColumn",
             name: "Americas",
             showInLegend: true,
             yValueFormatString: "#,##0 MW",
             dataPoints: <?php echo json_encode($dataPoints3, JSON_NUMERIC_CHECK); ?>
         },{
             type: "stackedColumn",
             name: "China",
             showInLegend: true,
             yValueFormatString: "#,##0 MW",
             dataPoints: <?php echo json_encode($dataPoints4, JSON_NUMERIC_CHECK); ?>
         },{
             type: "stackedColumn",
             name: "Middle East and Africa",
             showInLegend: true,
             yValueFormatString: "#,##0 MW",
             dataPoints: <?php echo json_encode($dataPoints5, JSON_NUMERIC_CHECK); ?>
         },{
             type: "stackedColumn",
             name: "Rest of the world",
             showInLegend: true,
             yValueFormatString: "#,##0 MW",
             dataPoints: <?php echo json_encode($dataPoints6, JSON_NUMERIC_CHECK); ?>
         }
     ]
 });
  
 chart.render();
  
 function toggleDataSeries(e) {
     if (typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
         e.dataSeries.visible = false;
     } else {
         e.dataSeries.visible = true;
     }
     e.chart.render();
 }
  
 }
 </script>

 <div id="chartContainer" style="height: 200px; width: 100%;"></div>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>

And the output am getting is
Output am Getting

Output needed

So the main problem is am having vertical stacked bar graph , but what i need is horizontal stack graph

ignore some data fields while export json data into excel from xlsx in react

I am using xlsx package to export JSON data(which is coming from the backend) to an excel file, right now all data of JSON are used for making the excel sheet which makes the excel sheet corrupt, Is there any way to restrict some data to not included in the excel sheet.

Here is my code which export JSON to Excel

function Workbook() {
    if (!(this instanceof Workbook))
        return new Workbook()

    this.SheetNames = []

    this.Sheets = {}
}

const download = (url, name) => {
    let a = document.createElement('a')
    a.href = url
    a.download = name
    a.click()

    window.URL.revokeObjectURL(url)
}


function s2ab(s) {
    const buf = new ArrayBuffer(s.length)

    const view = new Uint8Array(buf)

    for (let i=0; i !== s.length; ++i)
        view[i] = s.charCodeAt(i) & 0xFF

    return buf
}

export const DownloadExcel= (data,filename) => {
    import('xlsx').then(XLSX => {
        const wb = new Workbook()
        const ws = XLSX.utils.json_to_sheet(data)

        wb.SheetNames.push('')
        wb.Sheets[''] = ws


        const wbout = XLSX.write(wb, {bookType:'xlsx', bookSST:true, type: 'binary'})


        let url = window.URL.createObjectURL(new Blob([s2ab(wbout)], {type:'application/octet-stream'}))

        download(url, filename)
    })
}

Make possible close a popup, opened with :target , clicking on a overlay link tag

I created a popup with pseudoclass :target and it works properly.

<!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>
    <style>
      body {
        font-family: "Open Sans", sans-serif;
        padding: 0;
        margin: 0;
      }
      h2 {
        color: #2062ae;
      }

      a.btn {
        display: block;
        margin: 0px auto;
        border: 1px solid #2062ae;
        padding: 10px 20px;
        color: #2062ae;
        width: 100px;
        transition: 0.4s;
        text-decoration: none;
        text-align: center;
      }

      a.btn:hover {
        background: #2062ae;
        color: white;
      }

      .popup {
        max-width: 500px;
        margin: 0 auto;
        text-align: center;
      }

      #popup {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: #999;
        opacity: 0;
        transition: 1s;
        z-index: -1;
      }

      #popup:target {
        opacity: 1;
        z-index: 2;
      }

      .popup-content {
        position: absolute;
        top: 50%;
        left: 50%;

        /* min-height: 35%;
        width:50%;
        line-height: 1.5; */
        /* word-break: break-all; */
        transform: translate(-50%, -50%);
        padding: 20px 10px;
        background: rgb(238, 235, 235);
        border: 5px ridge orange;
        font-size: smaller;
      }

      .close-popup {
        position: absolute;
        top: -1em;
        left: -1em;
        width: 2em;
        height: 2em;
        border-radius: 50%;
        line-height: 2em;
        text-align: center;
        background-color: #ccc;
        text-decoration: none;
        color: black;
      }

      video {
        width: 100%;
        height: auto;
        display: block; /* Necessario altrimenti visualizza una striscia bianca in basso */
      }
    </style>
  </head>
  <body>
    <div class="popup">
      <h2>Pure CSS Popup</h2>
      <a href="#popup" class="btn">Apri Popup</a>
    </div>
    <div id="popup">
      <div class="popup-content">
        <p>
          Lorem ipsum dolor sit amet consectetur adipisicing elit. Veritatis
          iure numquam quia dolores voluptates repellat qui, incidunt in, enim
          id laborum doloribus odio rem sed fuga ratione totam? Laboriosam,
          ipsam.
        </p>
        <!-- Attribute muted necessario altrimenti Google Chrome potrebbe impedire l'autoplay -->
        <!--  <video src="video.mp4" autoplay muted controls></video> -->
        <a href="#" class="close-popup" aria-label="chiudi">X</a>
      </div>
    </div>

    <!-- <script>
      let closeLink = document.querySelector(".close-popup");
      closeLink.onclick = stoppaVideo;

      function stoppaVideo() {
        document.getElementsByTagName("video")[0].pause();
      }
    </script> -->
  </body>
</html>

However I would make possible click on the background/overlay element and close the popup. For this purpose I transformated the div element (#popup) in a tag but in this way doesn’t work. How could I resolve, and why doesn’t work like that?
Below the code that doesn’t work.

<!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>
    <style>
      body {
        font-family: "Open Sans", sans-serif;
        padding: 0;
        margin: 0;
      }
      h2 {
        color: #2062ae;
      }

      a.btn {
        display: block;
        margin: 0px auto;
        border: 1px solid #2062ae;
        padding: 10px 20px;
        color: #2062ae;
        width: 100px;
        transition: 0.4s;
        text-decoration: none;
        text-align: center;
      }

      a.btn:hover {
        background: #2062ae;
        color: white;
      }

      .popup {
        max-width: 500px;
        margin: 0 auto;
        text-align: center;
      }

      #popup {
        display:block;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: #999;
        opacity: 0;
        transition: 1s;
        z-index: -1;
      }

      #popup:target {
        opacity: 1;
        z-index: 2;
      }

      .popup-content {
        position: absolute;
        top: 50%;
        left: 50%;

        /* min-height: 35%;
        width:50%;
        line-height: 1.5; */
        /* word-break: break-all; */
        transform: translate(-50%, -50%);
        padding: 20px 10px;
        background: rgb(238, 235, 235);
        border: 5px ridge orange;
        font-size: smaller;
      }

      .close-popup {
        position: absolute;
        top: -1em;
        left: -1em;
        width: 2em;
        height: 2em;
        border-radius: 50%;
        line-height: 2em;
        text-align: center;
        background-color: #ccc;
        text-decoration: none;
        color: black;
      }

      video {
        width: 100%;
        height: auto;
        display: block; /* Necessario altrimenti visualizza una striscia bianca in basso */
      }
    </style>
  </head>
  <body>
    <div class="popup">
      <h2>Pure CSS Popup</h2>
      <a href="#popup" class="btn">Apri Popup</a>
    </div>
    <a href="#" id="popup">
      <div class="popup-content">
        <p>
          Lorem ipsum dolor sit amet consectetur adipisicing elit. Veritatis
          iure numquam quia dolores voluptates repellat qui, incidunt in, enim
          id laborum doloribus odio rem sed fuga ratione totam? Laboriosam,
          ipsam.
        </p>
        <!-- Attribute muted necessario altrimenti Google Chrome potrebbe impedire l'autoplay -->
        <!--  <video src="video.mp4" autoplay muted controls></video> -->
        <a href="#" class="close-popup" aria-label="chiudi">X</a>
      </div>
    </a>

    <!-- <script>
      let closeLink = document.querySelector(".close-popup");
      closeLink.onclick = stoppaVideo;

      function stoppaVideo() {
        document.getElementsByTagName("video")[0].pause();
      }
    </script> -->
  </body>
</html>

PrimeFaces.monitorDownload not calling the stop function

after porting my application from PF 8.0 to PF 11.0 with PrimeFaces.monitorDownload, the stop method is not called.

<h:form id="pdfExportForm">

    <h:commandLink id="pdfExportLink" action="#{statisticsAdminController.exportPDF}"  style="display: none;"
                   onclick="PrimeFaces.monitorDownload(showStatus, hideStatus);" />

    <p:dialog modal="true" widgetVar="statusDialog" draggable="false" closable="false">
        <p:graphicImage library="images" name="ajax-loader.gif" />
    </p:dialog>

</h:form>

the exportPDF method calls the method that downloads the file

    public static void downloadFile (
                                         ByteArrayOutputStream  baos
                                        ,FacesContext           fctx
                                        ,String                 fileName
                                        ,String                 contentType
                                    ) throws IOException
    {
        ExternalContext ectx    = fctx.getExternalContext();
        OutputStream    out     = ectx.getResponseOutputStream();

        ectx.responseReset();
        ectx.setResponseContentType(contentType);
        ectx.setResponseHeader("Expires", "0");
        ectx.setResponseHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        ectx.setResponseHeader("Pragma", "public");
        ectx.setResponseHeader("Content-disposition", "attachment;filename=" + fileName);
        ectx.setResponseContentLength(baos.size());
        ectx.addResponseCookie(Constants.DOWNLOAD_COOKIE, "true", Collections.<String, Object> emptyMap());
        baos.writeTo(out);
        fctx.responseComplete();
        ectx.responseFlushBuffer();
        out.close();
    }

this code works fine with PF 8.0, but after porting to PF 11.0 I end up with a modal dialog that does not close after the download finishes. However the file gets downloaded.

Best Regards
Andrija

Nest.JS DTO Validation

My DTO is

 @Expose()
 @IsNotEmpty()
 @IsJSON({ each: true })
 filesRole: string

filesRole is something like that: [{"file": "14125.png", "role": "bg"}, {"file": "x12.png", "role": "cover"}]

I want to validate role to be bg or cover.

Why “REPL command prompt” doesn’t work as expected?

I’m reading nodejs documentation but sometimes my code doesn’t work as the doc expected.

ex. Run REPL from javascript file
as the doc said, I’m adding the following code in my repl.js file:

const repl = require('repl');
const local = repl.start(prompt);

Then, running the file in the command line:

node repl.js

BUT

unfortunately, I’m facing an error!!!

const local = repl.start(prompt);
                         ^
ReferenceError: prompt is not defined

Am I doing something wrong here?

How to make a cleaner code that counts multiple button clicks using vanilla JS?

I’m using a counter for button clicks and it’s working fine, but I would like to ask how I can make it cleaner and less repetitive and still do the same function?

To give a perspective, I’m using this to track usage of hundreds of buttons, therefore the code can look really messy if I stick to use my current script.

How would I go about and make this simpler and cleaner?

    function clickCounter1() {
        if (typeof (Storage) !== "undefined") {
            if (localStorage.clickcount1) {
                localStorage.clickcount1 = Number(localStorage.clickcount1) + 1;
            } else {
                localStorage.clickcount1 = 1;
            }
            document.getElementById("result1").innerHTML = "Btn 1: " + localStorage.clickcount1;
        }
    }
    function clickCounter2() {
        if (typeof (Storage) !== "undefined") {
            if (localStorage.clickcount2) {
                localStorage.clickcount2 = Number(localStorage.clickcount2) + 1;
            } else {
                localStorage.clickcount2 = 1;
            }
            document.getElementById("result2").innerHTML = "Btn 1: " + localStorage.clickcount2;
        }
    }
    function clickCounter3() {
        if (typeof (Storage) !== "undefined") {
            if (localStorage.clickcount3) {
                localStorage.clickcount3 = Number(localStorage.clickcount3) + 1;
            } else {
                localStorage.clickcount3 = 1;
            }
            document.getElementById("result3").innerHTML = "Btn 1: " + localStorage.clickcount3;
        }
    }
<button onclick="clickCounter1()" type="button">Click me!</button>
<button onclick="clickCounter2()" type="button">Click me!</button>
<button onclick="clickCounter3()" type="button">Click me!</button>

<br>

<div id="result1"></div>
<div id="result2"></div>
<div id="result3"></div>

Important functions are just two:

  1. Count the clicks for each button
  2. Store in local storage

Thank you very much in advance!

remove function in not working in java script why [closed]

I am getting problems with removing a id that is in an HTML page and I am removing it from javascript

with remove function and its working giving errors

document.getElementbyId(‘id-name”).remove();
give’s typeError on chrome browser

i tryed removechild(element)
and remove(element);
removechild(element);

Targeting the last odd element with a given class

I have a dynamic photo list, pulled from the CMS. Photos are vertical and horizontal. I am trying to create a “dynamic grid” where all horizontal photos are 100% wide and vertical photos are 50% wide.
I was able to achieve this with the help of JS.
codepen with my code

However, I have trouble targeting the last odd vertical shot that has a horizontal shot in front of it. I would like this photo to be 100% wide as well, so that there would be no unnecessary break.

I tried to use :nth-child() pseudo class but, that was not helpful at all. – its select only first child.

.wide + .portfolio-item:nth-last-child(odd) {
  width: 100%;
}

How to send bulk get requests using nodejs?

I wrote a web crawler with nodejs to send get requests to about 300 urls.
Here is the main loop:

for (let i = 1; i <= 300; i++) { 
    let page= `https://xxxxxxxxx/forum-103-${i}.html`
    await getPage(page,(arr)=>{
        console.log(`page ${i}`)
    })
}

Here is the function getPage(url,callback):

export default async function getPage(url, callback) {
    await https.get(url, (res) => {
        let html = ""
        res.on("data", data => {
            html += data
        })
        res.on("end", () => {
            const $ = cheerio.load(html)
            let obj = {}
            let arr = []
            obj = $("#threadlisttableid tbody")
            for (let i in obj) {
                if (obj[i].attribs?.id?.substr(0, 6) === 'normal') {
                    arr.push(`https://xxxxxxx/${obj[i].attribs.id.substr(6).split("_").join("-")}-1-1.html`)
                }
            }
            callback(arr)
            console.log("success!")
        })
    })
        .on('error', (e) => {
            console.log(`Got error: ${e.message}`);
        })
}

I use cheerio to analyze HTML and put all information i need to variable nameed ‘arr’.
The program will report an error after running normally for a period of time,like that:

...
success!
page 121
success!
page 113
success!
page 115
success!
Got error: connect ETIMEDOUT 172.67.139.206:443
Got error: connect ETIMEDOUT 172.67.139.206:443
Got error: connect ETIMEDOUT 172.67.139.206:443
Got error: connect ETIMEDOUT 172.67.139.206:443
Got error: connect ETIMEDOUT 172.67.139.206:443
Got error: connect ETIMEDOUT 172.67.139.206:443

I have two questions:

1.What is the reason for the error? Is it because I am sending too many get requests? How can I limit the request frequency?

2.As you can see, The order in which the pages are accessed is chaotic,how to control them?

I have tried using other modules to send get request (such as Axios) but it didn’t work.