Trouble passing key to AES encryption/decryption functions – CryptoJS

I can succesfully generate a key using a WordArray and log it to the console.
But when passing the encryptionKey to my encryption function it gets lost somewhere.
I generate the key in the encrypt function, pass it to a global variable so it may be used in the decryption function as well.
The line const encrypted = CryptoJS.AES.encrypt(plainText, encryptionKey); is where I’m suspecting the problem may lie. The plainText variable is indeed a string and is not undefined or null.

I wanted to generate a random key, using CryptoJS’ WordArray.random(256/8), pass it to a global instance of the variable for later use in the decryption.

Key should be passed from one scope to the other and allow for the encryption function to run
The whole thing works fine if I pass my encryption function a hardcoded key as a string instead.

My JavaScript

(function() {
    let encryptionKey;

    document.getElementById("encryptBtn").addEventListener("click", encrypt); 
    document.getElementById("decryptBtn").addEventListener("click", decrypt);
    
    function encrypt() { // Encrypt userinput plaintext in ID:cipherText
        encryptionKey = CryptoJS.lib.WordArray.random(256/8);
        console.log("encryptionKey", encryptionKey);

        const plainText = document.getElementById("plainText").value; 
        console.log("plaintext", plainText);

const encrypted = CryptoJS.AES.encrypt(plainText, encryptionKey);
        const encryptedString = encrypted.toString();
        console.log("encrypted", encryptedString);

        document.getElementById("cipherText").value = encryptedString; 
        console.log("Ciphertext:" + cipherText);
    }
    
    function decrypt() { // Decrypt userinput plaintext in ID:decryptedText
        const cipherText = document.getElementById("cipherText").value;
        const decrypted = CryptoJS.AES.decrypt(cipherText,                                                                             encryptionKey).toString(CryptoJS.enc.Utf8);
        document.getElementById("decryptedText").value = decrypted;
    }
})();

How i ac fetch state country data in dropdownlist from api

I am creating a user registration project, i have created backend(API), the backend is working very well.
On frontend, I am using reactJS. I can show user details such as name email gender etc. but the problem occurs when i am tring to show state and country.
I am unable to show state country in dropdownlist

here is API–

{
  "registerData": [
    {
      "_id": "65dcae2a012ff8648e1e2307",
      "name": "Iron Man",
      "address": "Avengers",
      "email": "[email protected]",
      "password": "Avenger#16",
      "gender": "Male",
      "subscribe": true,
      "city": {
        "_id": "65dcac3f012ff8648e1e2300",
        "name": "Gorapkpur",
        "state": {
          "_id": "65dca9b1957aa055730d3969",
          "name": "UP",
          "country": {
            "_id": "65dca9521cf1da91bebd7bf1",
            "name": "India",
            "__v": 0
          },
          "__v": 0
        },
        "__v": 0
      },
      "__v": 0
    },
    {
      "_id": "65dcae41012ff8648e1e2309",
      "name": "Natasha",
      "address": "Avengers",
      "email": "[email protected]",
      "password": "Natash#16",
      "gender": "Female",
      "subscribe": false,
      "city": {
        "_id": "65dcac3f012ff8648e1e2300",
        "name": "Gorapkpur",
        "state": {
          "_id": "65dca9b1957aa055730d3969",
          "name": "UP",
          "country": {
            "_id": "65dca9521cf1da91bebd7bf1",
            "name": "India",
            "__v": 0
          },
          "__v": 0
        },
        "__v": 0
      },
      "__v": 0
    },
    {
      "_id": "65dcb57f8ced231c34b1f714",
      "name": "SpiderMan",
      "address": "Avengers",
      "email": "[email protected]",
      "password": "spider#16",
      "gender": "Male",
      "subscribe": true,
      "city": {
        "_id": "65dcac3f012ff8648e1e2300",
        "name": "Gorapkpur",
        "state": {
          "_id": "65dca9b1957aa055730d3969",
          "name": "UP",
          "country": {
            "_id": "65dca9521cf1da91bebd7bf1",
            "name": "India",
            "__v": 0
          },
          "__v": 0
        },
        "__v": 0
      },
      "__v": 0
    }
  ]
}

how i can bind city, state and country in dropdown list??

Error Handling in Service Worker When response.ok is False

I’m a novice in JS & functional programming. I need to implement a service worker to cache static assets. In the following code what should be done when the response.ok is false?

    ev.respondWith(
      fetch(ev.request)
        .then((res) => {
          if (res.ok) {
            // this part is done and working
          } else {
            // what should be done here? Should the response be returned
            // and let the UI handle the error, like the following?
            return res;
            // or nothing?
          }
        })
        .catch((err) => caches.match(ev.request).then((res) => res))
    );

Your help will be greatly appreciated.

Overflow-x:auto not working inside a grid layout on fieldset at max-width media query

I’m experiencing an issue where overflow-x: auto; on a fieldset element is not triggering a horizontal scrollbar within a media query. The fieldset contains multiple div elements displayed as a grid, and I expect a horizontal scrollbar to appear when the viewport width is less than 480px.

important info: This is an A/B test being run on a Shopify store

Here’s the media query and relevant CSS:

@media screen and (max-width: 480px) {
  fieldset[name="Color"] {
    background-color: red;
    display: grid;
    grid-auto-flow: column;
    column-gap: 0.5em;
    overflow-x: auto !important;
    width: 100%;
    max-width: 100%;
  }

  fieldset[name="Color"] div label {
    white-space: nowrap;
  }
}

However, the content overflows the viewport without triggering a scrollbar. I’ve attempted to set overflow-x: visible; on the body and html tags to ensure that they aren’t constraining the fieldset, but this resulted in the entire page allowing horizontal overflow, which is not desired.

I’ve attached a screenshot:enter image description here showing the overflowing div elements within the fieldset in the DOM.

I have also tried:

Adding min-width on grid items.
Ensuring no parent elements have overflow-x: hidden;.
Using box-sizing: border-box; globally.
Removing the mediaQuery
Removing custom scrollbar styling.

I would appreciate any insights or solutions to achieve a horizontal scrollbar on the fieldset when the content overflows at a viewport width of less than 480px without causing the whole page to scroll horizontally.

Troubleshooting MVC Implementation: Item Details Not Displaying When Clicking on Index Items

I recently implemented the MVC architecture in my web application to manage items. In the index page, users can see a list of items, and I want to display the details of each item when they click on it. However, despite following MVC principles and configuring routes and controllers, the item details are not displaying as expected.

Error: 404 Error

The server cannot locate /item/shirt2

Here’s a breakdown of the issue:

When clicking on an item in the index page, the item details should be displayed.
I’ve set up routes to handle requests for specific item details and controllers to fetch and render the data.
The client-side JavaScript code seems to be correctly extracting the item ID and constructing the URL for fetching details.
Despite these efforts, the item details are not appearing when I click on an item. I suspect there might be a problem with the routing, data retrieval, or client-side JavaScript code, but I’m having trouble pinpointing the exact cause.

Can anyone provide insights into common pitfalls or potential issues to look out for when implementing MVC architecture for handling item details in a web application? Any advice on troubleshooting steps or specific areas to focus on would be greatly appreciated. Thank you!

Route

router.get('/item/:id', controller.show);

controller

exports.show = (req, res) => {
const itemId = req.params.id;
const item = model.findById(itemId);
if (item) {
    res.render('./items/item', { item });
} else {
    // Handle case where item is not found
    res.status(404).send('Item not found');
}};

index.ejs

<section class="shirts">
<% items.forEach(item => { %>
<div class="shirt" id="<%= item.id %>">
    <a href="/item/<%= item.id %>">
        <img src="<%= item.imageSrc %>" alt="<%= item.title %>">
        <h2><%= item.title %></h2>
    </a>
    <h4>Condition: <%= item.condition %></h4>
    <h3><%= item.price %></h3>
    <% if (item.numOffers > 0) { %>
        <h5>Offer</h5>
        <ul>
        <% item.offers.forEach(offer => { %>
            <li><%= offer.buyer %> offered <%= offer.offerAmount %></li>
        <% }); %>
        </ul>
    <% } else { %>
        <h5>No Offers</h5>
    <% } %>
</div>
<% }); %>

Set input text value and set data value in checkboxes in javascript

So, I am using a snippet to change the value of input texts and checkboxes (tick them) based on a dictionary. So, we are talking about very common questions. If the question (span above the input text) is Age, it should return the number. If the question is Gender, it should tick the relevant box underneath and make sure it is true before submitting the form (google form for this example). I noticed that for every questions box document.querySelector("#mG61Hd > div.RH5hzf.RLS9Fe > div > div.o3Dpx > div:nth-child(2) > div > div") has an id. So, the id equals the child plus X where X = 3 and then every time it increases to X+3:

5 = 2 + 3
9 = 3 + 6
13 = 4 + 9
17 = 5 + 12

document.addEventListener("DOMContentLoaded", function() {
// Define the dictionary with keys and values you want to return
const myself = {
  "Full Name": "My Name",
  "Phone": "07666444500",
  "Age": "26",
  "Email": "[email protected]",
  "Gender": "Female",
  "Ethnicity":"White British"
};

  for (let i = 1; i <= 50; i++) { 
    let hId = "#i" + ((i - 1) * 4 + 1);
    let hElement = document.querySelector(`${hId} > span.M7eMe`);
    let h = hElement ? hElement.textContent.trim() : null; 

    let inputSelector = `#mG61Hd > div.RH5hzf.RLS9Fe > div > div.o3Dpx > div:nth-child(${i}) > div > div > div.AgroKb > div > div.aCsJod.oJeWuf > div > div.Xb9hP > input`;
    let inputElement = document.querySelector(inputSelector);

    if (myself[h]) {
      if (inputElement && inputElement.type === "radio") {
        let radioGroup = document.querySelectorAll(`input[name='${inputElement.name}']`);
        for (let j = 0; j < radioGroup.length; j++) {
          if (radioGroup[j].value.toLowerCase() === myself[h].toLowerCase()) {
            radioGroup[j].checked = true;
            break;
          }
        }
      } else if (inputElement) {
        inputElement.value = myself[h];
      } else {
        let radioDiv = document.querySelector(`div[role='radio'][data-value='${myself[h]}']`);
        if (radioDiv) {
          radioDiv.click();
        }
      }

      if (inputElement) {
        inputElement.dispatchEvent(new Event('input', { bubbles: true }));
      }
    }
  }
});
<form action="https://docs.google.com/forms/u/0/d/e/1FAIpQLSf4dPFtGUXJVuMnMmZYgFsbFaDnZ8ED4tiiYV4ENObHfRYyPQ/formResponse" target="_self" method="POST" id="mG61Hd" jsmodel="TOfxwf Q91hve CEkLOc" data-shuffle-seed="-5791707696025457682" data-clean-viewform-url="https://docs.google.com/forms/d/e/1FAIpQLSf4dPFtGUXJVuMnMmZYgFsbFaDnZ8ED4tiiYV4ENObHfRYyPQ/viewform?usp=sf_link" data-response="%.@.]" data-dlp-data="%[email protected],false]" data-first-entry="0" data-last-entry="18" data-is-first-page="true">

  <div class="RH5hzf RLS9Fe">
    <div class="lrKTG">
      <div class="o3Dpx" role="list">
        <div class="Qr7Oae" role="listitem">
          <div jsmodel="CP1oW" data-params="%.@.[1145350593,&quot;Full Name&quot;,null,0,[[988383412,null,true,null,null,null,null,null,null,null,[]]],null,null,null,null,null,null,[null,&quot;Full Name&quot;]],&quot;i1&quot;,&quot;i2&quot;,&quot;i3&quot;,false]">
            <div jscontroller="sWGJ4b" jsaction="EEvAHc:yfX9oc;" jsname="WsjYwc" class="geS5n">
              <div class="z12JJ">
                <div class="M4DNQ">
                  <div id="i1" class="HoXoMd D1wxyf RjsPE" role="heading" aria-level="3" aria-describedby="i4">
                    <span class="M7eMe">Full Name</span>
                    <span class="vnumgf" id="i4" aria-label="Required question"> *</span>
                  </div>
                  <div class="gubaDc OIC90c RjsPE" id="i2"></div>
                </div>
              </div>
              <div jscontroller="oCiKKc" jsaction="rcuQ6b:vZc4S;O22p3e:zjh6rb;b2trFe:eVidQc;sPvj8e:d3sQLd;AHmuwe:h06R8;" class="AgroKb">
                <div class="rFrNMe k3kHxc RdH0ib yqQS1 zKHdkd" jscontroller="pxq3x" jsaction="clickonly:KjsqPd; focus:Jt1EX; blur:fpfTEe; input:Lg5SV" jsshadow="" jsname="YPqjbf">
                  <div class="aCsJod oJeWuf">
                    <div class="aXBtI Wic03c">
                      <div class="Xb9hP">
                        <input type="text" class="whsOnd zHQkBf" jsname="YPqjbf" autocomplete="off" tabindex="0" aria-labelledby="i1" aria-describedby="i2 i3" aria-disabled="false" required="" dir="auto" data-initial-dir="auto" data-initial-value="">
                      </div>
                      <div class="i9lrp mIZh1c"></div>
                      <div jsname="XmnwAc" class="OabDMe cXrdqd"></div>
                    </div>
                  </div>
                  <div class="LXRPh">
                    <div jsname="ty6ygf" class="ovnfwe Is7Fhb"></div>
                  </div>
                </div>
              </div>
              <div jsname="Rfh2Tc" class="SL4Sz" id="i3" role="alert"></div>
            </div>
          </div>
        </div>
        <div class="Qr7Oae" role="listitem">
          <div jsmodel="CP1oW" data-params="%.@.[611627761,&quot;Phone&quot;,null,0,[[89548986,null,true,null,null,null,null,null,null,null,[]]],null,null,null,null,null,null,[null,&quot;Phone&quot;]],&quot;i5&quot;,&quot;i6&quot;,&quot;i7&quot;,false]">
            <div jscontroller="sWGJ4b" jsaction="EEvAHc:yfX9oc;" jsname="WsjYwc" class="geS5n">
              <div class="z12JJ">
                <div class="M4DNQ">
                  <div id="i5" class="HoXoMd D1wxyf RjsPE" role="heading" aria-level="3" aria-describedby="i8">
                    <span class="M7eMe">Phone</span>
                    <span class="vnumgf" id="i8" aria-label="Required question"> *</span>
                  </div>
                  <div class="gubaDc OIC90c RjsPE" id="i6"></div>
                </div>
              </div>
              <div jscontroller="oCiKKc" jsaction="rcuQ6b:vZc4S;O22p3e:zjh6rb;b2trFe:eVidQc;sPvj8e:d3sQLd;AHmuwe:h06R8;" class="AgroKb">
                <div class="rFrNMe k3kHxc RdH0ib yqQS1 zKHdkd" jscontroller="pxq3x" jsaction="clickonly:KjsqPd; focus:Jt1EX; blur:fpfTEe; input:Lg5SV" jsshadow="" jsname="YPqjbf">
                  <div class="aCsJod oJeWuf">
                    <div class="aXBtI Wic03c">
                      <div class="Xb9hP">
                        <input type="text" class="whsOnd zHQkBf" jsname="YPqjbf" autocomplete="off" tabindex="0" aria-labelledby="i5" aria-describedby="i6 i7" aria-disabled="false" required="" dir="auto" data-initial-dir="auto" data-initial-value="">
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="Qr7Oae" role="listitem">
          <div jsmodel="CP1oW" data-params="%.@.[1244337291,&quot;Age&quot;,null,0,[[1920163779,null,true,null,null,null,null,null,null,null,[]]],null,null,null,null,null,null,[null,&quot;Age&quot;]],&quot;i9&quot;,&quot;i10&quot;,&quot;i11&quot;,false]">
            <div jscontroller="sWGJ4b" jsaction="EEvAHc:yfX9oc;" jsname="WsjYwc" class="geS5n"></div>
          </div>
        </div>
      </div>
    </div>
  </div>

</form>

It seems to be working in the snippet but it does not overall. I have saved everything in a snippet to prove it:

https://jsfiddle.net/radomer/p5xc6rdz/

where you can see that some values change and some others do not. I can definitely not see the radio boxes being ticked. I have been trying different version but I fail. Where is the main issue of this? Is it based on my calculation of ids? Is it also because I have to change the tabindex and aria-checked to true for the checkbox questions?

PS: For the purpose of cutting down HTML code, I removed some questions. The same applies for the jsfiddle and the snippet.

No way to step into node_modules anymore?

Is it just me, or Chromium DevTools stopped to stop at breakpoints in node_modules (including /usr/lib/node_modules)?

a.js:

console.log('a.js');
require('./b');

b.js:

debugger
console.log('b.js');
require('userhome');
$ npm i [email protected]
// add the following lines to node_modules/userhome/index.js:
// debugger
// console.log('userhome');
$ node --inspect-brk a.js

Open about:inspect in Chromium. Choose the process under Remote Target. Press F8. It stops at b.js. Press F8 again. It doesn’t stop at node_modules/userhome/index.js and finishes.

Am I missing something? Is there a way to debug this issue somehow (a way to figure out why it doesn’t stop at node_modules breakpoints)?

I’m running Chromium 121.0.6167.184 and nodejs v21.6.1.

setting object property from api call to cached data in react

I am building an nba stat tracker app and i am working on a feature for the user to be able to save a team, and on a window reload or when the user revisits the app, i want the browser to be able to check a favoriteTeams state array to check if a team is in the favorites list and update an object property when the data is being fetched. on a window reload, the favorite teams state still contains the favorite teams, but the isFavorite property is not being set if the favoriteTeams state includes the team that is being loaded into the updatedTeams array.

fetch (/** api data */)
.then(res => res.json())
    .then(data => {
      const updatedTeams = data.response.map((team: Team) => {
        return {
          ...team,
          isFavorite: favoriteTeams.includes(team) 
        };
      });
      setTeams(updatedTeams);
    })
    .catch(err => window.alert("Could not load data. Refresh and try again"));
  }, [season]);

Instead of checking if the whole team object is in the favTeams state i checked the id but that also isnt working

Why is the first condition not being met? [closed]

I am applying for Northcoders bootcamp and I’m stuck with the if/else/ and switch statements. I’ll post the instructions, my code and the error messages I’m receiving. I would really appreciate it if someone could help me find what I’m doing wrong because as far as I can see the code should work correctly

Instructions

A bunch of Northcoders are planning their holidays, and are hoping to use this code to help them practice greetings in the language of the country they are visiting.

The code you write should assign a value to greeting that is correct depending on the country that is being visited and the time of day.

It is morning if the time is 0 or more, but less than 12. If the time is 12 or more, but less than 24, it is evening. If time is any other value, greeting should always be null, whatever the language.

If country is Spain or Mexico, greeting should be buenos dias in the morning and buenas noches in the evening. If country is France, greeting should be bon matin in the morning and bon soir in the evening. If country is any other value, greeting should always be null, whatever the time (we don’t have many languages in our dictionary yet…)

Just a reminder: you can use country and time in expressions just like any other variable. There are lots of ways you could solve this challenge! Use any tools you’ve learned so far.

function sayHello(country, time) {
    let greeting = null;

    if (time >= 0 && time < 12) {
        if (country === 'Spain') {
            greeting = 'buenos días';
        } else if (country === 'Mexico') {
            greeting = 'buenos días';
        } else if (country === 'France') {
            greeting = 'bon matin';
        }
    } else if (time >= 12 && time < 24) {
        if (country === 'Spain') {
            greeting = 'buenas noches';
        } else if (country === 'Mexico') {
            greeting = 'buenas noches';
        } else if (country === 'France') {
            greeting = 'bon soir';
        }
    }

    return greeting;
}

Error Information

9 Passing
2 Failing

Greeting should be correct for Spain in the morning

  ✕ AssertionError: expected 'buenos días' to equal 'buenos dias'

 

Greeting should be correct for Spain in the evening

    ✓  Well done!

 

Greeting should be null if the time is invalid in Spain

    ✓  Well done!

 

Greeting should be correct for Mexico in the morning

  ✕ AssertionError: expected 'buenos días' to equal 'buenos dias'

 

Greeting should be correct for Mexico in the evening

    ✓  Well done!

 

Greeting should be null if the time is invalid in Mexico

    ✓  Well done!

 

Greeting should be correct for France in the morning

    ✓  Well done!

 

Greeting should be correct for France in the evening

    ✓  Well done!

 

Greeting should be null if the time is invalid in France (remembering that 24 is an invalid time)

    ✓  Well done!

 

Greeting should be null if the time is invalid in France

    ✓  Well done!

 

Greeting should be null for other countries

    ✓  Well done!

Print styles: How to ensure image span pages if there are texts above the image

I am currently working on an issue with printing from a browser. I have a relatively large image with some descriptive text on top of it, and I want to ensure that when printing, the image appears at the bottom of the page and get split. Because the size of the image is too large, it will automatically flow to the next page, causing a lot of blank space below the text.

What I’d like

Page 1 |                    |
       |  (text text text)  |
       |  (text text text)  |
       |  ________________  |
       | | Top of image   | |
       |____________________|
       ------page break------
        ____________________
Page 2 | | Rest of image  | |
       | |________________| |
       |         …          |

What I see now

Page 1 |                    |
       |  (text text text)  |
       |  (text text text)  |
       |                    |
       |                    |
       |                    |
       |                    |
       |                    |
       |                    |
       |____________________|
       ------page break------
        ____________________
Page 2 | |                | |
       | |                | |
       | |     image      | |
       | |                | |
       | |----------------| |
               ....

slider javascript error – reading style undefined

I am having an error regarding a slider and am unsure how to fix it, i tried all thing s i know, can someone shed some light please where i have gone wrong?

var slideIndex = 0;
   showSlides();

  function showSlides() {
    var i;
    var slides = document.getElementsByClassName("mySlides");
    for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none";
    }
    slideIndex++;
    if (slideIndex > slides.length) {
      slideIndex = 1;
    }

   slides[slideIndex - 1].style.display = "block";
    setTimeout(showSlides, 2000); // Change image every 2 seconds
  }
.home-container { 
margin: 0px auto; // center
width:100%; 
text-align:center; 
overflow:hidden;
background-size: contain;

} 

@media only screen and (max-width: 600px) {
    .home-container {
        width:100%;
    }
    
    
}
.slideshow-container {
   width: auto;
    height:100%;
    margin: auto;
    position: relative;
   
}

.mySlides {
  display:none;
    width: 100%;
}

.text {
  color: rgb(245,205,245);

  font-size: 30px;
  position: bottom;
  bottom: 8px;
  width: 100%;
  text-align: center;
        
}


.fade {
  animation-name: fade;
  animation-duration: 1.5s;
    align-content: center;
}

@keyframes fade {
  from {opacity: .4}
  to {opacity: 1}
}
<div class="home-container">

        <div class="slider-container">
                  
          <div class="mySlides fade">
            <a href="businesses.html"> 
            <img
              src="Media/slider/Main1.jpg" class="responsive-img"
              alt="Bohemia Creative Quarter" ></a> 
            <div class="text">Bohemia Creative Quarter</div>
              
          </div>
          <div class="mySlides fade">
            <a href="businesses.html"> 
            <img
              src="Media/slider/2111.jpg" class="responsive-img"
              alt="Painting" ></a>
              <div class="text">The Moth</div>
        </div>
          <div class="mySlides fade">
            <a href="businesses.html"> 
            <img
              src="Media/slider/166.jpg" class="responsive-img"
              alt="Pottery"></a>
              <div class="text">The Mudworks</div>
        </div>
          <div class="mySlides fade">
            <a href="businesses.html"> 
            <img
              src="Media/slider/Forage21.jpeg" class="responsive-img"
              alt="Flower Image"></a>
              <div class="text">Forage and Fleur</div>
            </div>
            <div class="mySlides fade">
           <a href="businesses.html"> 
            <img
              src="Media/slider/6.jpg" class="responsive-img"
              alt="Fancy Dress" ></a>
            <div class="text">Teddy Tinkers</div>
            </div> 
            <div class="mySlides fade">
          <a href="businesses.html"> 
            <img
              src="Media/slider/101.jpg" class="responsive-img"
              alt="Crystals" ></a>
            <div class="text">The Crystal Catalyst</div>
            </div>
            <div class="mySlides fade">
         <a href="businesses.html"> 
            <img
              src="Media/slider/71.jpg" class="responsive-img"
              alt="Rings" ></a>
            <div class="text">Silver Swann</div>
            </div>
           </div> 
        
    
       </div>
        

I understand it is related to the display.block but as mentioned I am unsure how to fix this. I have been stuck with this error for days and it is becoming very frustrating

html2canvas image to jsPDF renders element sizes differently between browsers

I’m using html2canvas and jsPDF libraries to generate a PDF export. For lack of a better term, Safari and Chrome respectively are “seeing” the size of elements differently.
Safari vs Chrome render size console messages

Another clue is that the SVGs are oversized in Safari.

SVG render difference in pdfs

So despite having set page, window, and canvas sizes manually, the rendered sizes differ. Is there a parameter I’m missing to force resolution or something else so this behaves consistently no matter what browser runs this? (dpi setting doesn’t appear to do anything. scale setting doesn’t “resize”, just makes img blurry if less than 1.)

export async function downloadPDFScorecard(printContent, fileName) {
  // const jsPDF = require('jspdf');
  console.info("download scorecard!");
  const imgWidth = 1142; 
  const pageHeight = 800;  
  const pageWidth = 1142;
  const marginY = 80;
  
  const jsPDFOpt = {
    orientation: 'l',
    unit: 'px',
    //[595.28, 841.89] is a4
    format: [pageHeight, pageWidth], 
    // putOnlyUsedFonts:true,
    compress: false,
    floatPrecision: 16 // or "smart", default is 16
   }

  const html2canvasOpt = {
    dpi: 300, // Set to 300 DPI
    scale: 1.2, // Adjusts your resolution
    width: 1142,
    height: 1256,
    windowWidth: 1142,
    windowHeight: 1256,
    x: 0,
    y: 0,
    logging: true,
    allowTaint: true,
    useCORS: true,
    removeContainer: true
  }

  await html2canvas(printContent, html2canvasOpt).then( (canvas) => {
      const imgHeight = canvas.height * imgWidth / canvas.width;
      let heightLeft = imgHeight;
      const positionX = 70;
      let positionY = 40;
      var img = canvas.toDataURL("image/jpeg", 1);
      var doc = new jsPDF(jsPDFOpt);
      // (inner) addImage(imageData, format, x, y, width, height, alias, compression, rotation)
      console.log("pg 1", {positionX, positionY, imgWidth, imgHeight})
      doc.addImage(img, 'JPEG', positionX, positionY, imgWidth, imgHeight, 'NONE', 0);

      heightLeft -= pageHeight;
      positionY = -730;
      console.log("pg 2", {positionX, positionY, imgWidth, imgHeight})
      doc.addPage().addImage(img, 'JPEG', positionX, positionY, imgWidth, imgHeight);

      doc.save(`${fileName}.pdf`);
  });

}

How to add Image + Text in button Value onClick?

I have a button and on click on it the text changes and I want to include Image with it and don’t know how, I’m new with JavaScript, help please!

<input onclick="change()" type="button" id="pay-btn" value="Click here to check" />
function change()
{
  document.getElementById("pay-btn").value="'https://i.stack.imgur.com/kOnzy.gif' please wait...";
}

I tried to search on StackOverflow and Google but don’t find a way to do this.

C++ Post request library doesn’t send json body or form data

I am trying to communicate with my NodeJS express rest API thru my c++ desktop application using HTTPRequest library by elnormous. I am on windows.

I tried doing json body, and form data post requests using this library and it doesn’t work. And I don’t know if I am doing something wrong.

First attempt (Using form data post request):

    try {
        http::Request request{ "http://0.0.0.0/get-confirmations" };
        const std::string body = "shared_secret=" + account.shared_secret + "&identity_secret=" + account.identity_secret;
        const auto response = request.send("POST", body, {
            {"Content-Type", "application/x-www-form-urlencoded"}
        });
        std::cout << std::string{ response.body.begin(), response.body.end() } << 'n'; // print the result
    } catch (const std::exception& e) {
        std::cerr << "Request failed, error: " << e.what() << 'n';
    }

Second attempt (Using json body post request):

    try {
        http::Request request{ "http://0.0.0.0/get-confirmations" };
        const std::string body = "{"shared_secret":"" + account.shared_secret + "","identity_secret":"" + account.identity_secret + ""}";
        const auto response = request.send("POST", body, {
            {"Content-Type", "application/json"}
        });
        std::cout << std::string{ response.body.begin(), response.body.end() } << 'n'; // print the result
    } catch (const std::exception& e) {
        std::cerr << "Request failed, error: " << e.what() << 'n';
    }

This is what my NodeJS express rest API code looks like:

import express from "express";

const port = 3000;

const app = express();

app.get('/', (req, res) => {
    const { name } = req.query;

    res.send('Hello world | Name: ' + name);
});

app.post('/get-confirmations', (req, res) => {
    console.log("query", req.query);
    console.log("body", req.body);

    const { shared_secret, identity_secret } = req.query;

    if (!shared_secret || !identity_secret) {
        return res.status(400).send('Missing shared_secret or identity_secret');
    }

    return res.send('Hello world | Shared Secret: ' + shared_secret + ' | Identity Secret: ' + identity_secret);
});

app.listen(port, () => {
    console.log(`[server]: Server is running at http://localhost:${port}`);
});