Make Chrome Extension Bigger

I recently made a chrome extension, but for some reason, when you first click it it appears very small. Small

My code:

#dif {
  width: 400px;
  height: 400px;
  font-size: 40px;
  color: black;
  text-align: center;
  font-weight: bold;
  padding: 100px;
  border: 5px solid black;
  border-radius: 20px;
  background-color: red;
  background-repeat: no-repeat;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Dif is the name of the box that is supposed to appear.

How to check if HTML5 FileSystemDirectoryHandle points to an existing directory

Lets say I have a refetence to a FileSystemDirectoryHandle, obtained by showDirectoryPicker(), which might have been deleted (at some point in time after referencing). What is the proper API to check if it points to an existing directory?

I can try-catch for await (const entry of directory.values()) but I wonder if there is something more appropriate.

I was thinking of using getDirectoryHandle but I do not have parent reference, nor does it accept empty name argument.

Changing text on mouseover for an SVG map

I am trying to change the text in the bubbles to different data on hover and having some difficulties. I want to be able to hover over a state and have the info for that state display in the red bubbles. Each state will have different information, and I am already using a tooltip to display the state name above it. I am currently using jQuery for the tooltip.

svg map

Clone contenteditable div without text

How can I clone a new row without also copying the text that has been inserted inside the contenteditable div? I want a new blank div to type into. Many thanks

<div id="wrapper">
  <div id="row">
    <p><strong>Heading</strong></p>
    <div contenteditable="true" data-placeholder="Type here..."></div>
  </div>
</div>
<button id="button" onlick="duplicate()">Add another row</button>
document.getElementById('button').onclick = duplicate;

var i = 0;
var original = document.getElementById('row');

function duplicate() {
    var clone = original.cloneNode(true);
    clone.id = "row" + ++i;
    original.parentNode.appendChild(clone);
}

HTML/JS Kanban Board doesn’t let me drop newly created tasks into other columns

I am creating a Kanban Board in HTML/JS/CSS and am close to finishing my MVP here. Everything is working as expected, except for one thing. When I create a new task, I am able to drag it (seemingly) but not DROP it into any other columns. The sample tasks I have do not have this problem and I am ripping my hair out trying to figure out what the issue is. When I attempt to drag and drop newly created tasks into other columns, I get this error:

TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
    at drop (/script.js:31:13)
    at HTMLDivElement.ondrop (/:45:112)

I am using basic drag and drop API stuff for HTML and JS and literally only need to make this work in order to finish my MVP. Any help is appreciated. NOTE: The line numbers in the above error change based on what column I try to drop the new task into but the error itself stays the same.

Here is my code:

index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Christopher's Kanban Board</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <div class="new-task-window" id="new_task_form">
      <div class="header">
        <div class="title">New Task</div>
        <button class="btn-close-window" data-target="#new_task_form">X</button>
      </div>
      <div class="body">
        <input type="text" id="new-task-name" />
        <input type="submit" value="New Task" id="new-task-submit" />
      </div>
    </div>

    <!--Kanban Board-->
    <div class="kanban-container">
      <div class="kanban-container-section" id="todo" ondrop="drop(event)" ondragover="allowDrop(event)">
        <strong>To Do</strong>
        <div class="task-button-block">
            <button class="task-button" id="task-button" data-target="#new_task_form">+ New Task</button>
        </div>
        <div class="task" id="task1" draggable="true" ondragstart="drag(event)">
          <span contenteditable="true">Task #1</span>
            <!--<button class="edit_button" id="edit_button">Edit</button>-->
        </div>
        <div class="task" id="task2" draggable="true" ondragstart="drag(event)">
          <span contenteditable="true">Task #2</span>
        </div>
        <div class="task" id="task3" draggable="true" ondragstart="drag(event)">
          <span contenteditable="true">Task #3</span>
        </div>
        <div class="task" id="task4" draggable="true" ondragstart="drag(event)">
          <span contenteditable="true">Task #4</span>
        </div>



      </div>
      <div class="kanban-container-section" id="inprogress" ondrop="drop(event)" ondragover="allowDrop(event)">
        <strong>In Progress</strong>

      </div>
      <div class="kanban-container-section" id="done" ondrop="drop(event)" ondragover="allowDrop(event)">
        <strong>Done</strong>

      </div>
      <div class="kanban-container-section" id=" blocked" ondrop="drop(event)" ondragover="allowDrop(event)">
        <strong>Blocked</strong>

      </div>
    </div>
    <div id="overlay"></div>
    <script src="script.js"></script>
  </body>
</html>

script.js:

const task = document.querySelector('.task');
const buttons = document.querySelectorAll("[data-target]");
const close_buttons = document.querySelectorAll(".btn-close-window");

//Allow the New Task Button to open the New Task Creation Window.
buttons.forEach(btn => {
  btn.addEventListener('click', () => {
    document.querySelector(btn.dataset.target).classList.add("active");
    overlay.classList.add("active");
  });
});

close_buttons.forEach((btn) => {
  btn.addEventListener('click', () => {
    document.querySelector(btn.dataset.target).classList.remove("active");
    overlay.classList.remove("active");
  });
});

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
}

const new_task_submit = document.getElementById("new-task-submit");
if(new_task_submit) {
  new_task_submit.addEventListener('click', createTask);
}

function createTask() {
  const task_div = document.createElement("div");
  const input_value = document.getElementById("new-task-name").value;

  //Take the text from the above input and create a task with that text.
  const text = document.createTextNode(input_value);

  task_div.appendChild(text);
  //Add the proper class (task in this case) to the newly created task.
  task_div.classList.add("task");
  //Add the draggable attribute to the newly created task and set it to true to allow drag and drop.
  if(task_div){
    task_div.setAttribute("draggable", "true");
    task_div.setAttribute("contenteditable", "true");
  }

  //task_div.innerHTML += `
  //<div class="task" id="${input_value.toLowerCase().split(" ").join("")}"
  //draggable="true" ondragstart="drag(event)>
    //<span contenteditable="true">${input_value}</span>
  //</div>
  //`

  //Add the new task to the To Do section of the Kanban Board.
  const todo = document.getElementById("todo");
  todo.appendChild(task_div);

  document.getElementById("new-task-name").value = "";
  new_task_form.classList.remove("active");
  overlay.classList.remove("active");

}

style.css (the error would indicate that this file is not the problem):

.kanban-container {
  display: grid;
  grid-auto-columns: 250px;
  grid-auto-flow: column;
  grid-gap: 8px;
  height: 100vh;
  overflow: auto;
}

.kanban-container-section {
  background: #EBEBEB;
  border-radius: 3px;
  display: grid;
  grid-auto-rows: max-content;
  grid-gap: 10px;
  padding: 10px;
}

.kanban-container-section strong {
  background: #2C89BF;
  font-size: 16px;
  margin: 0 0 12px 0;
  padding: 10px;
}

.task {
  background: #FFFFFF;
  box-shadow: 0 1px 0 rgba(9,30,66,.25);
  border-radius: 3px;
  padding: 10px;
}

.task-button {
  width: 40%;
  background: #FFFFFF;
  border-radius: 3px;
  box-shadow: 0 1px 0 rgba(9,30,66,.25);
  border: 0.1rem;
  cursor: pointer;
}

.task.button:active {
  transform: scale(0.9);
}

.btn-close-window {
  padding: 0.5rem 1rem;
  border: 1px solid #ccc;
  border-radius: 3px;
  cursor: pointer;
}

.new-task-window {
  width: 450px;
  position: fixed;
  top: -50%;
  left: 50%;
  transform: translate(-50%, -50%);
  border: 1px solid #ccc;
  z-index: 2;
  background-color:#FFFFFF;
}

.new-task-window.active {
  top: 15%;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5rem 1rem;
  background-color: rgba(0, 0, 0, 0.03);
  border-bottom: 1px solid #ccc;
}

#overlay {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.2);
}

#overlay.active {
  display: block;
}

#new-task-name, #new-task-submit {
  padding: 1rem 1rem;
  width: 90%;
  margin: 0.25rem;
  align-items: center;
}

#new-task-submit {
  background-color: #2C89BF;
  border: none;
  color: #FFFFFF;
  align-items: center;
}

Again, if anyone knows what my issue is here, the help is greatly appreciated. Thanks!

Javascript display none property not being triggered the second time

I am using onlick method on a button, on game start and re start. I am making the button’s parent node’s display none on that click. It works the first time when I click (i.e start the game) but after the game is over, when I try to re start the game using the same button, the display:none property is not working.

HTML part of the button and it’s parent node

<div class="game-start-play" id="game-start-play">
            <button id="play-start">Click to play</button>
          </div>

In javascript part, I am clicking the button, then doing some animation and when the animation stops, when I try to re start it the display none property is not working.

const startButton = document.getElementById("play-start");

const gameAnimation = new GameAnimation(parentElement);
window.addEventListener("keydown", gameAnimation.moveCar);

startButton.onclick = () => {
  startButton.parentNode.style.display = "none";
  gameAnimation.init();
};

How to change the size of graph dynamically for React

Although I want to change the size of the graph dynamically using React, it doesn’t work. Why?

It appears values that was input in the forms are immediately reflected in the state. However, these values are reflected in “width” and “height” in Google Charts.
How should I do in order to immediately reflect in the parameter of the Google Charts?

import React, {useState, useEffect} from 'react';
import ReactDOM from 'react-dom';
import {Chart} from 'react-google-charts';

const App = () => {
    const [W, setW] = useState('100');
    const [H, setH] = useState('100');

    useEffect(() => {
        console.log('useEffect was run.');
        console.log('W=' + W);
        console.log('H=' + H);
    });

    const handleChangeW = (e) => {
        setW(e.target.value);
        console.log('handleChangeW was run -> ' + e.target.value + '(' + W + ')');
    }

    const handleChangeH = (e) => {
        setH(e.target.value);
        console.log('handleChangeH was run -> ' + e.target.value + '(' + H + ')');
    }

    return(
        <>
        <h1>Google Chart Test</h1>
        <hr />
        W: <input type="text" onChange={handleChangeW} value={W} /><br />
        H: <input type="text" onChange={handleChangeH} value={H} />
        <hr />
        <Output W={W} H={H} />
        </>
    );
}

const Output = (p) => {
    const W = p.W + 'px';
    const H = p.H + 'px';
    console.log('W==' + W);
    console.log('H==' + H);

    return (
        <>
            W: {W}<br />
            H: {H}<br />
            <hr />
            <Chart
                    width={W}
                    height={H}
                    chartType="LineChart"
                    loader={<div>Loading Chart</div>}
                    data={[
                    [
                        'aaa', 'bbb', 'ccc','ddd','eee','ffff', 'gggg','hhhhh'
                    ],
                        [1, 100, 90, 110, 85, 96, 104, 120],
                        [2, 120, 95, 130, 90, 113, 124, 140],
                        [3, 130, 105, 140, 100, 117, 133, 139],
                        [4, 90, 85, 95, 85, 88, 92, 95],
                        [5, 70, 74, 63, 67, 69, 70, 72],
                        [6, 30, 39, 22, 21, 28, 34, 40],
                        [7, 80, 77, 83, 70, 77, 85, 90],
                        [8, 100, 90, 110, 85, 95, 102, 110],
                    ]}
                    options={{
                    intervals: { style: 'sticks' },
                    legend: 'none',
                    }}
            />
        </>
    );
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
)

google.script.run.WithSuccessHandler returning the script completed but did not return anything

I am not seeing where the issue is in my code, that prevents it from returning the success message. I want to give me the message that the submission has been successful and to refresh the screen. While the data is being successfully submitted to the google sheet, I am getting the generic message that the script is completed but didn’t return anything.

var ss = SpreadsheetApp.openById('XXXXX');
var sheet = ss.getSheetByName('Messages');
var thisDocumentURL =ss.getUrl();
var ShtAdmin = "[email protected]";


function doPost(e){
  // Replace with your spreadsheet's ID.
  
  // name, phone_number and e-mail are form elements.
  var area = e.parameter.area;
  var assembly = e.parameter.assembly;
  var pass = e.parameter.pass;
  var line = e.parameter.line;
  var operator = e.parameter.operator;
  var shift = e.parameter.shift;
  var issueDescription = e.parameter.issueDescription;
  var personNotified = e.parameter.personNotified;
  var actionTaken = e.parameter.actionTaken;
  var personTakingAction = e.parameter.personTakingAction;
  var problemCorrected = e.parameter.problemCorrected;
  var approvalToContinue = e.parameter.approvalToContinue;
  var issueCategory = e.parameter.issueCategory;
  var id = getRandom();
  var timestamp = new Date(); // current date as epoch number
  

  sheet.appendRow(
    [id,timestamp,area,assembly,pass,line,operator,shift,issueDescription,personNotified,actionTaken,personTakingAction,problemCorrected,approvalToContinue,issueCategory,message]
  );
  
  var subject = "PEP Log Update";
  var header = "<p> This is an Automated mailer.  All Responses are directed to " + ShtAdmin+",</p>";
  var message = "<p><b>There has been an addition to the PEP log on "+ timestamp + ". </b></p>"+
                "<p><b>Associated with "+assembly +" running on Line " + line + ", "+pass+" pass. </p></b>";

MailApp.sendEmail({

  to: ShtAdmin,
  noReply: true,
  subject: subject,
  htmlBody: header + message 
})

onSuccess(message);
  
var pubUrl = ScriptApp.getService().getUrl();


}  //end of doPost Function


function getSuccessMessage(message){
  //Logger.log(data);
  return("PEP Successfully submitted.");
}

function onSuccess(){
  getSuccessMessage();
  var message = "You have successfully submitted the PEP.  Please refresh screen to reset form.";
  return message;
}



HTML Portion

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=chrome">
    <link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/ css/add-ons1.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"  crossorigin="anonymous" ></script>
    <title>Google Apps Script Tester</title>
  
</head>

<body>
    <form method="post" action= "<?= pubUrl ?>" >
    <form id="myForm">
             
        <label for="area">Select Area:</label>
        <select name="area" id="area">
        <option value="AOI">AOI</option>
        <option value="SMT">SMT</option>
        </select>
        <br><br>    
        Assembly: <input type="assembly" name="assembly" value=""><br><br>
        
        <label for="pass">Pass:</label>
        <select name="pass" id="pass">
        <option value="1st">1st</option>
        <option value="2nd">2nd</option>
        <option value="Single">Single</option>
        </select><br><br>
        <label for="line">Line:</label>
        <select name="line" id="line">
        <option value="Line 1/2">Line 1/2</option>
        <option value="Line 3">Line 3</option>
        <option value="Line 4">Line 4</option>
        <option value="Line 7">Line 7</option>
        <option value="Line 8">Line 8</option>
        <option value="Line 10">Line 10</option>
        </select>
        <br><br> 
        Employee Number: <input type="operator" name="operator" value=""><br><br>
        <label for="shift">Shift:</label>
       
        <label for="problemCorrected">Issue Corrected:</label>
        <select name="problemCorrected" id="problemCorrected">
        <option value="Yes">Yes Continue to Run</option>
        <option value="No-Escalate to Supervisor">No - Escalate to Supervisor</option>
        <option value="No-Conintue to Run with Approval">No - Continue to run with Approval</option>
        </select><br><br> 
        Approval to run w/o resolving issue: <input type="approvalToContinue" name="approvalToContinue" value=""><br><br>
        <label for="issueCategory">Issue Category:</label>
        <select name="issueCategory" id="issueCategory">
        <option value="Material Problem">Material Problem</option>
        <option value="Equipment Issue">Equipment Issue</option>
        <option value="Human Error">Human Error</option>
        <option value="Other">Other</option>    
        </select><br><br> 
        
        <br><br><br>
        <p>Please Click to submit data.</p>              
        <button type="submit" id="mySubmit" onClick="">Send Data</button>
        <p id="response_message"></p>
        
<script>
      const scriptURL = <?= pubUrl ?>
      const form = document.forms['myForm']
      google.script.run.withSuccessHandler(onSuccess);
      function onSuccess(message){
        var div = document.getElementById('response_message');
           }
      return response_message;
     form.addEventListener('submit', e => {
      e.preventDefault()
      var response_message = document.getElementById("response_message");
      fetch(scriptURL, { method: 'POST', body: new FormData(form)})
      .then(response => response_message.innerHTML = "Success!  Refresh screen for new form")
      .catch(error => response_message.innerHTML = "Error!")

    
        }
      })
    </script>

  
        



</form>
</form>

</body></html>

Track the actions that led to a multi-level drop down menu to open

Goal:

Track all the actions required to reach a certain level in a multi-level dropdown.

Example:

A multi-level dropdown like https://s.bootsnipp.com/iframe/xr4GW which can be opened by hovering on it. Once a menu item is clicked on the dropdown, how can one figure out what hover actions led to that part of the menu being opened ?

In the above bootsnip demo, if the first link in level 3 is clicked on, I want to be able to say that:

  • 3rd link in level 1
  • –> 2nd link in level 2, resulted in being able to
  • —-> click the 1st link in level 3

Current direction:

Currently I’m using mouseover and click events to see if I can some-how co-relate all the events together. But no luck as of yet.


Thank you in advance πŸ™‚

Calling functions only for the current page – Datatables

I’m having a little issue with my DataTable ( DataTables.js ). I’m trying to get some images from a PHP function by an AJAX call.
I want to call the function only for the current page, not for the whole table. I tried placing “deferRender: true” inside “DataTable” and inside “columnDefs”, but is not working. It’s still called for the whole table

Code:

        $('#CategoriProductsTable').DataTable( {
            data: data, // Getting all the data
            deferRender: true, // Useless
            columnDefs: [ 
                {
                    targets: 0,
                    "data": function (data, type, dataToSet) { // This function I want to call it only for the current page, not for the entier table.
                        $.ajax({
                            url: "/core/pagination/produse.pagination.php",
                            type: "post",
                            data: {
                                GetArticleImage:        "Yes",
                                ArticleID:              data.part_number,
                                SupplierID:             data.supplier_id,
                                SupplierName:           data.supplier_name
                            },
                        }).done(function (data) {
                            return data;
                            //$(currentCell).html(data);
                        });
                        //return '<img class="manufacturers-logo" src="/resources/assets/images/logos/'+data.supplier_id+'.jpg" alt="'+data.supplier_name+'">'+data.supplier_name;
                   }
                },
                // IGNORE FROM HERE
                {
                "targets": [ 1 ],
                "data": "supplier_name"
                // Merge
                //"data": function (data, type, dataToSet) {
                //    return '<img class="manufacturers-logo" src="/resources/assets/images/logos/'+data.supplier_id+'.jpg" alt="'+data.supplier_name+'">'+data.supplier_name;
                //    }
                },
                {
                "targets": [ 2 ],
                "data": "part_number"
                }
            ]
    } );

Yup string length test validation with <= and not ===

I’m trying to check to see if a string is less than or equal to 30 characters with Yup and react-hook-form in TypeScript.

I’ve found this example on SO to check if a string length === 5 and it works great, with just the type of error handling messaging I’m looking for.

The cited example validation works as expected when applied in my schema

title: Yup.string().test('len', 'Title must be exactly 5 characters', val => val?.length === 5).required('Title is required')

But with a change for my case (checking to see if the string is less than or equal to 30) I get an Object is possibly undefined error, even though I believe th ? should be covering the undefined case

title: Yup.string().test('len', 'Title must be less than or equal to 30 characters', val => val?.length <= 30).required('Title is required')

What’s different between the use of === and <= in this case?

Thanks

Upload blob with AJAX and move file in the server

I started the project to create a social network with my little programming skills, but I’m stuck:
I want to create a posting system like Facebook / Instagram, but the problem is, I want to be able to upload images given by my users to the server directly and not to the database. So I first looked for a way I needed to preview the image, for that I converted the image to Base64 using JS then, I displayed it in my img tag. Then users could submit the form, that’s where it gets complicated, because if I understood correctly, you have to convert the image into a Blob to be sent by AJAX so that’s what I do in JS except that after it arrived in the PHP file I couldn’t find a way to turn it back to Base64 as I realized that PHP doesn’t support Blobs or if it does manage it then I was wrong, and I have not found a way to exploit this technology in PHP. So here I am, sending the data is working, no problem, but I still can’t upload the images to my server directly, so I tried doing a base64_encode(); but it didn’t work, then I tried multiple code from the whole web, but it still didn’t work. I saw that on this site there were multiple questions that demand for the same help, but after reading them all well, but in practice it still didn’t work, so hopefully I could find some help here and my code after will work. I leave you the code below, and thank you for reading everything. πŸ™‚
Sorry I forgot two things, I wouldn’t want to use jQuery in my code, that’s why if you give me jQuery I’ll try to translate to normal JS, but it’s going to be rather difficult so if you don’t mind please do not use jQuery. And for the second thing please forgive my English I am a French in high school passionate about code and given that the whole site is in English I did not allow myself to write in French πŸ™‚
My code :

var getHttpRequest = function () {

     var httpRequest = false;

     if (window.XMLHttpRequest) { //Mozilla,Safari,...

          httpRequest = new XMLHttpRequest();

          if (httpRequest.overrideMimeType) {

               httpRequest.overrideMimeType('text/xml');

          }

     }

     else if (window.ActiveXObject) { //IE

          try {
               httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
          }

          catch (e) {
                         
               try{

                    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
               }

               catch (e) {}
          }
     }
     if (!httpRequest) {
          alert('Abandon :( Impossible de crΓ©er une instance XMLHTTP');
          return false;
     }

     return httpRequest;
}
function creapubimg(){
    let httpRequest = getHttpRequest();
    let content = document.getElementById('content_text_area_img').value;
    let imgpub = document.getElementById('chosen-image').src;
    let extention = ['jpeg','png','jpg','gif'];
    let base64ImageContent,contentType,hashtxt;
    var contentTypepost
    let idcountforinclude=0;
    extention.forEach(element => {
        if (imgpub.indexOf(element.value) !== -1){
            base64ImageContent = imgpub.replace('data:image/'+element.value+';base64');
            switch (element.value) {
                case 'jpeg':
                case 'jpg':
                    contentTypepost = 2;
                    contentType = 'image/jpeg'
                    break;
                case 'png':
                    contentTypepost = 3;
                    contentType = 'image/png'
                    break;
                case 'gif':
                    contentTypepost = 1;
                    contentType = 'image/gif'
                    break;
                default:
                    break;
            }
        }
    });
    let base64 = imgpub.replace('data:image/jpeg;base64,', "");
    let blob = b64toBlob(base64,contentType);
    let blobUrl = URL.createObjectURL(blob);
    hashtxt = makeid(24);
    httpRequest.onreadystatechange = function (){
        if(httpRequest.readyState === 1){
          hide_img_panel_reverse();
        }
        if(httpRequest.readyState === 2){
          // faire apparaitre truc de chargment
        }
        if(httpRequest.readyState === 4){
            if(httpRequest.responseText != 'veuiller remplir tout les champs'){
                idcountforinclude += 1;
                let docu = document.getElementById('aff_pub');
                // hide truc de chargment
                let replt = document.createElement('div');
                replt.setAttribute('id', idcountforinclude);
                docu.prepend(replt);
                document.getElementById(idcountforinclude).innerHTML = httpRequest.responseText;
            }
        }
    }
    httpRequest.open('POST','includes/createpubimg.php',true);
    httpRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    httpRequest.send("content_publiction=" + encodeURIComponent(content) + "&img=" + encodeURIComponent(blob) + "&string=" + encodeURIComponent(hashtxt) + "&Content-Type=" + encodeURIComponent(contentTypepost));
}
function b64toBlob(b64Data, contentType='',sliceSize=512){
    let byteCharacters = atob(b64Data);
    let byteArrays = [];
    for(let offset = 0; offset <  byteCharacters.length; offset+=sliceSize){
        
        let slice = byteCharacters.slice(offset,offset + sliceSize);
        let byteNumbers = new Array(slice.length);
        for (let i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }
        let byteArray = new Uint8Array(byteNumbers);
        byteArrays.push(byteArray);
    }
    let blob = new Blob(byteArrays, {type: contentType});
    return blob;
}

And here is the PHP :

<?php
include '../database.php';
        global $db;

if(isset($_POST['img'])){
  if($_POST['Content-Type'] == 1) {
    $hashchemin = crypt($_POST['string'], 'piafou');
    $hashchemin = rtrim($hashchemin, '/\');
    $chemin = 'img_pub/'.$hashchemin.'.gif';  
    if(isset($_POST['content_publication'])){
      if(!empty($_POST['content_publication'])){
        $content = $_POST['content_publication'];
        $Blobimg = $_POST['file'];
        $Base64img = "data:image/png;base64," . base64_encode($Blobimg) . "";
        move_uploaded_file(base64_decode($Base64img), $chemin);
        $ins = $db->prepare('INSERT INTO publications (content, img_pub) VALUES (:content, :img_pub)');
        $ins->execute([
          'content' => $content,
          'img_pub' => $chemin
        ]);
        $publications =$db->query('SELECT * FROM publications ORDER BY id DESC LIMIT 60');
        $pub = $publications->fetch();
        ?>
          <div class="aff_pub_div_content" id="<?=$pub['id']?>">
            <div style="height: 52px;">
              <img class="nonSelectionnable" height="48px" width="48px" src="IMG/favicon.png" style="float: left; margin-left: 16px">
              <label class="nonSelectionnable" style="float: left; margin-left: 8px;margin-top: 12px;font-size: 20px;">Nerzus</label>
              <a class="button-edit nonSelectionnable" onclick="hide_edit_panel(<?= $pub['id'] ?>)" style="text-decoration: none; color: #807c7cc4; margin-right: 20px; font-size: 12.6px; float: right; cursor: pointer;">●●●</a>
            </div>
            <div class="nonSelectionnable">
              <?php if(!empty($pub['img_pub'])){ ?>
                <img src="<?=$pub['img_pub']?>" class="img_pub_aff">
              <?php 
                  }
              ?>
            </div>
            <div>
              <p class="text_pub_aff" id="<?="content_".$pub['id']?>">
                <?php 
                  $pub_content = $_POST['content_publication'];
                  $pub_content = htmlspecialchars($pub_content, ENT_HTML5);
                  $pub_content = nl2br($pub_content);
                  echo($pub_content);
                ?>  
              </p>
            </div>
            <div style="background-color:#d6d6dd;height:1px;width:96%;margin-top:10px; margin-right:auto;margin-left:auto;"></div>
            <div style="text-align: left;" class="nonSelectionnable">
              <ul style="margin-top: 6px; margin-left: 20px">
                <?php 
                  $likepub = $db->prepare('SELECT * FROM like_pub WHERE pub = :pub AND user = :user');
                  $likepub->execute([
                    'user' => 16,
                    'pub' => $pub['id']
                  ]);
                  if($likepub->rowCount() ==1) {
                ?> 
                <style type="text/css">
                  .phpdecidelikecolordiv-<?=$pub['id']?>{
                    background-color: red;
                  }
                </style>
                <?php
                  }
                  else{
                ?>
                <style type="text/css">
                  .phpdecidelikecolordiv-<?=$pub['id']?>{
                    background-color: white;
                  }
                </style>
                <?php
                  }
                ?>
                <li class="exp_article" style="margin-right: 6px">
                  <div style="height: 30px;width: 30px;" class="like_article phpdecidelikecolordiv-<?=$pub['id']?>" id="like-div-<?=$pub['id']?>">
                    <a style="cursor: pointer;" onclick="like_db(16,<?=$pub['id']?>,<?=$pub['id']?>);">
                      <img src="IMG/love.png" height="30px" width="30px" id="like">
                    </a>
                  </div>
                </li>
                <li class="exp_article" style="color: black;font-size: 24px;font-family: 'Oswald', sans-serif;;vertical-align: top;margin-top: -3px; margin-right: 16px;" id="likepart-<?=$pub['id']?>"><?php $idpublike = $pub['id'];$likerecup = $db->prepare('SELECT * FROM like_pub WHERE pub = :id');$likerecup->execute(['id' => $idpublike]);$likecount = $likerecup->rowCount();echo $likecount;?></li>
                <li class="exp_article">
                  <div style="background-color:white;height: 30px;width: 30px;" class="comment_article" id="comment-div-<?=$pub['id']?>"><a style="cursor: pointer;" onclick="comment_aff(<?=$pub['id']?>);"><img src="IMG/chat-bubble.png" height="30px" width="30px" id="comment"></a></div>
                </li>
              </ul>
            </div>
          </div>
        <?php
      }
      else{
        echo('Veuiller remplir tout les champs');
      } 
    }
  }
  elseif($_POST['Content-Type'] == 2){
    $hashchemin = crypt($_POST['string'], 'piafou');
    $hashchemin = rtrim($hashchemin, '/\');
    $chemin = 'img_pub/'.$hashchemin.'.jpeg';
    if(isset($_POST['content_publication'])){
      if(!empty($_POST['content_publication'])){
        $content = $_POST['content_publication']; 
        $Blobimg = $_POST['file'];
        $Base64img = "data:image/png;base64," . base64_encode($Blobimg) . "";
        move_uploaded_file(base64_decode($Base64img), $chemin);
        $ins = $db->prepare('INSERT INTO publications (content, img_pub) VALUES (:content, :img_pub)');
        $ins->execute([
          'content' => $content,
          'img_pub' => $chemin
        ]);
        $publications =$db->query('SELECT * FROM publications ORDER BY id DESC LIMIT 60');
        $pub = $publications->fetch();
        ?>
          <div class="aff_pub_div_content" id="<?=$pub['id']?>">
            <div style="height: 52px;">
                <img class="nonSelectionnable" height="48px" width="48px" src="IMG/favicon.png" style="float: left; margin-left: 16px">
                <label class="nonSelectionnable" style="float: left; margin-left: 8px;margin-top: 12px;font-size: 20px;">Nerzus</label>
                <a class="button-edit nonSelectionnable" onclick="hide_edit_panel(<?= $pub['id'] ?>)" style="text-decoration: none; color: #807c7cc4; margin-right: 20px; font-size: 12.6px; float: right; cursor: pointer;">●●●</a>
            </div>
            <div class="nonSelectionnable">
              <?php if(!empty($pub['img_pub'])){ ?>
                <img src="<?=$pub['img_pub']?>" class="img_pub_aff">
              <?php 
                  }
              ?>
            </div>
            <div>
              <p class="text_pub_aff" id="<?="content_".$pub['id']?>">
                <?php 
                  $pub_content = $_POST['content_publication'];
                  $pub_content = htmlspecialchars($pub_content, ENT_HTML5);
                  $pub_content = nl2br($pub_content);
                  echo($pub_content);
                ?>  
              </p>
            </div>
            <div style="background-color:#d6d6dd;height:1px;width:96%;margin-top:10px; margin-right:auto;margin-left:auto;"></div>
            <div style="text-align: left;" class="nonSelectionnable">
              <ul style="margin-top: 6px; margin-left: 20px">
                <?php 
                  $likepub = $db->prepare('SELECT * FROM like_pub WHERE pub = :pub AND user = :user');
                  $likepub->execute([
                    'user' => 16,
                    'pub' => $pub['id']
                  ]);
                  if($likepub->rowCount() ==1) {
                ?> 
                <style type="text/css">
                  .phpdecidelikecolordiv-<?=$pub['id']?>{
                    background-color: red;
                  }
                </style>
                <?php
                  }
                  else{
                ?>
                <style type="text/css">
                  .phpdecidelikecolordiv-<?=$pub['id']?>{
                    background-color: white;
                  }
                </style>
                <?php
                  }
                ?>
                <li class="exp_article" style="margin-right: 6px">
                  <div style="height: 30px;width: 30px;" class="like_article phpdecidelikecolordiv-<?=$pub['id']?>" id="like-div-<?=$pub['id']?>">
                    <a style="cursor: pointer;" onclick="like_db(16,<?=$pub['id']?>,<?=$pub['id']?>);">
                      <img src="IMG/love.png" height="30px" width="30px" id="like">
                    </a>
                  </div>
                </li>
                <li class="exp_article" style="color: black;font-size: 24px;font-family: 'Oswald', sans-serif;;vertical-align: top;margin-top: -3px; margin-right: 16px;" id="likepart-<?=$pub['id']?>"><?php $idpublike = $pub['id'];$likerecup = $db->prepare('SELECT * FROM like_pub WHERE pub = :id');$likerecup->execute(['id' => $idpublike]);$likecount = $likerecup->rowCount();echo $likecount;?></li>
                <li class="exp_article">
                  <div style="background-color:white;height: 30px;width: 30px;" class="comment_article" id="comment-div-<?=$pub['id']?>"><a style="cursor: pointer;" onclick="comment_aff(<?=$pub['id']?>);"><img src="IMG/chat-bubble.png" height="30px" width="30px" id="comment"></a></div>
                </li>
              </ul>
            </div>
          </div>
        <?php
      }
      else{
        echo('Veuiller remplir tout les champs');
      } 
    } 
  }
  elseif($_POST['Content-Type'] == 3){
    $hashchemin = crypt($_POST['string'], 'piafou');
    $hashchemin = rtrim($hashchemin, '/\');
    $chemin = 'img_pub/'.$hashchemin.'.png';
    if(isset($_POST['content_publication'])){
      if(!empty($_POST['content_publication'])){
        $content = $_POST['content_publication'];
        $Blobimg = $_POST['file'];
        $Base64img = "data:image/png;base64," . base64_encode($Blobimg) . "";
        move_uploaded_file(base64_decode($Base64img), $chemin);
        $ins = $db->prepare('INSERT INTO publications (content, img_pub) VALUES (:content, :img_pub)');
        $ins->execute([
          'content' => $content,
          'img_pub' => $chemin
        ]);
        $publications =$db->query('SELECT * FROM publications ORDER BY id DESC LIMIT 60');
        $pub = $publications->fetch();
        ?>
          <div class="aff_pub_div_content" id="<?=$pub['id']?>">
              <div style="height: 52px;">
                  <img class="nonSelectionnable" height="48px" width="48px" src="IMG/favicon.png" style="float: left; margin-left: 16px">
                  <label class="nonSelectionnable" style="float: left; margin-left: 8px;margin-top: 12px;font-size: 20px;">Nerzus</label>
                  <a class="button-edit nonSelectionnable" onclick="hide_edit_panel(<?= $pub['id'] ?>)" style="text-decoration: none; color: #807c7cc4; margin-right: 20px; font-size: 12.6px; float: right; cursor: pointer;">●●●</a>
              </div>
              <div class="nonSelectionnable">
                <?php if(!empty($pub['img_pub'])){ ?>
                  <img src="<?=$pub['img_pub']?>" class="img_pub_aff">
                <?php 
                    }
                ?>
              </div>
              <div>
                <p class="text_pub_aff" id="<?="content_".$pub['id']?>">
                  <?php 
                    $pub_content = $_POST['content_publication'];
                    $pub_content = htmlspecialchars($pub_content, ENT_HTML5);
                    $pub_content = nl2br($pub_content);
                    echo($pub_content);
                  ?>  
                </p>
              </div>
              <div style="background-color:#d6d6dd;height:1px;width:96%;margin-top:10px; margin-right:auto;margin-left:auto;"></div>
              <div style="text-align: left;" class="nonSelectionnable">
                <ul style="margin-top: 6px; margin-left: 20px">
                  <?php 
                    $likepub = $db->prepare('SELECT * FROM like_pub WHERE pub = :pub AND user = :user');
                    $likepub->execute([
                      'user' => 16,
                      'pub' => $pub['id']
                    ]);
                    if($likepub->rowCount() ==1) {
                  ?> 
                  <style type="text/css">
                    .phpdecidelikecolordiv-<?=$pub['id']?>{
                      background-color: red;
                    }
                  </style>
                  <?php
                    }
                    else{
                  ?>
                  <style type="text/css">
                    .phpdecidelikecolordiv-<?=$pub['id']?>{
                      background-color: white;
                    }
                  </style>
                  <?php
                    }
                  ?>
                  <li class="exp_article" style="margin-right: 6px">
                    <div style="height: 30px;width: 30px;" class="like_article phpdecidelikecolordiv-<?=$pub['id']?>" id="like-div-<?=$pub['id']?>">
                      <a style="cursor: pointer;" onclick="like_db(16,<?=$pub['id']?>,<?=$pub['id']?>);">
                        <img src="IMG/love.png" height="30px" width="30px" id="like">
                      </a>
                    </div>
                  </li>
                  <li class="exp_article" style="color: black;font-size: 24px;font-family: 'Oswald', sans-serif;;vertical-align: top;margin-top: -3px; margin-right: 16px;" id="likepart-<?=$pub['id']?>"><?php $idpublike = $pub['id'];$likerecup = $db->prepare('SELECT * FROM like_pub WHERE pub = :id');$likerecup->execute(['id' => $idpublike]);$likecount = $likerecup->rowCount();echo $likecount;?></li>
                  <li class="exp_article">
                    <div style="background-color:white;height: 30px;width: 30px;" class="comment_article" id="comment-div-<?=$pub['id']?>"><a style="cursor: pointer;" onclick="comment_aff(<?=$pub['id']?>);"><img src="IMG/chat-bubble.png" height="30px" width="30px" id="comment"></a></div>
                  </li>
                </ul>
              </div>
          </div>
        <?php
      }
      else{
        echo('Veuiller remplir tout les champs');
      } 
    }
  }
  else{
    // message d'erreur
  }
}
?>

You can see that in my PHP code I put this:

$Base64img = "data:image/png;base64," . base64_encode($Blobimg) . "";

It is thanks to this line of code that I believed that I would succeed in converting the blob to Base64
If anyone has the solution to my problem, I thank them in advance.
P.S. = I have already tried with Form Data and I have not succeeded I think this is the solution, but I cannot get it to work.
Thanks to everyone who read πŸ™‚

Puppeteer Calling Browser.close() randomly throws an a error that is not catchable – Error: EPERM: operation not permitted

I have stripped out all of the code in my app to isolate this issue and it can be reproduce by only launching the browser and calling browser.close(). The error thrown is [Error: EPERM: operation not permitted, unlink ‘C:UsersxxxAppDataLocalTemppuppeteer_dev_chrome_profile-vHZSchCrashpadMetrics-active.pma’] and it hangs the process. I need to be able to catch this error so the server can continue to process requests, however this error cannot be caught. How can I catch/prevent this error?

The error is thrown from the browser.close() call as mentioned is possible in the documentation here. I wrapped an additional try catch within the finally around that call and it doesn’t catch but throws the error.

try{
 browser = await puppeteer.launch({
   args: ['--no-sandbox', '--unlimited-storage', '--disable-gpu', '--disable-dev-shm-usage', '--full-memory-crash-report', '--disable-setuid-sandbox'],
   headless: true,
   pipe: true
 }).catch((err) => {
   console.log('could not launch browser', err)
 });
} catch(err) {
   console.error(err);
} finally {
  try{
    if(browser) {
      console.log('closing down browser')
      const pages = await browser.pages();
      console.log(pages.length)
      await Promise.all(pages.map(page => page.close()))
      console.log('closed pages')
      // if (browser && browser.process() !== null){
      //     browser.process().kill('SIGINT');
      // }
      await browser.close().catch((err) => console.log(err));
      console.log('finished closing')
    }
  }
  catch(error){
    console.log('this caught', error)
  }    
}

The commented out lines for killing the process do prevent the error from being thrown, however I am on a windows machine and this does not actually kill the process, although I imagine this method works on linux.

Getting error : “react-dom.production.min.js:216 TypeError: Object(…) is not a function” while deploying react app on github pages

I am trying to deploy my react application and its not rendering the page properly, It is throwing the below error : react-dom.production.min.js:216 TypeError: Object(…) is not a function.

I have linked the screenshot of the error and the file name along with my github link of the repo.[![

Expense.js

import { useState } from "react";
import "../css/Expenses.css";
import Card from "./Card";
import ExpenseItem from "./ExpenseItem";
import Filter from "./Filter";

function Expenses(props){
    let data = props.data;
    let [year,changeYear] = useState("2021");

    let data2 = data.filter(function(item){
      return(new Date(item.dates).getFullYear().toString() === year);
    })
    

    let setFilter = function(yearValue){
      changeYear(yearValue);
    }


    return(
     <Card className = "card">
     <div className="filter-section">
       <h3>Filter By Year</h3>
       <Filter sendData={setFilter} yearVal = {year} className='year-filter-card'/>
     </div>
     <div className="expense-wrap">
          {data2.length?
            data2.map(function(expItem) {
             return <ExpenseItem key={Math.random()*100000} item= {expItem} deleteMe={props.deleteMe}/>  
          }):
          <h2 className="nodata">No Expense Data</h2> 
    }
    </div>
     </Card>
    );
    
}

export default Expenses;

link to my repo: https://github.com/AbhishekTomr/money-tracker

Get Blob Content from bindings and then zip the content and save it in the blob container using azure function

I am using bindings of azure function to get the blob content and to store the file in blob.
Below is the code that I am using but its not passing anything to the output bindings.

const JSZip = require("jszip");
const saveas = require('file-saver')
module.exports = async function (context, myBlob) {
    context.log("Function Triggered. ", context.bindingData.blobTrigger);
        
 var input = context.bindings.myBlob;
     var inputBuffer = Buffer.from(input);
     var zip = new JSZip();
zip.file(inputBuffer);
zip.generateAsync({type:"blob"})
.then(function(content) {

 var j =   content;
  context.bindings.myOutputBlob = j; 
});
 
 
 
 }

Please let me know what I am doing wrong here.