Copying to clipboard within an iframe

I’m coding a script/extension for a browser game I’m currently playing. In the game you can press a button that automatically copies a code/string to your clipboard. I would like to modify said string.

The problem I am currently running into is that the game is hosted on a site that uses an iframe within an iframe and while I already have a working solution for the game itself (you can play the game by accessing the source url of the innermost iframe), trying to run this solution on the host site gives me the following error:

“undefined:The Clipboard API has been blocked because of a permissions policy applied to the current document. See goo.gl/EuHzyv for more details.”

I have already tried the approach outlined in this post, but it doesn’t work, so here is my question:

When using the solution in the linked post for nested iframes, what origin url needs to be used?

   <iframe src="url1" allow="clipboard-read; clipboard-write self [what url goes here]>
      <iframe src="url2" allow="clipboard-read; clipboard-write self [what url goes here]
         <canvas for game with button that copies something into clipboard>
      </iframe>
   </iframe>

What is this and who’s doing it!? Any ideas would be greatly appreciated. Thanks in advance [closed]

language=’javascript’ type=’text/javascript’> (function() { // Establish the root mraidbridge object. var mraidbridge = window.mraidbridge = {}; // Listeners for bridge events. var listeners = {}; // Queue to track pending calls to the native SDK. var nativeCallQueue = []; // Whether a native call is currently in progress. var nativeCallInFlight = false; ////////////////////////////////////////////////////////////////////////////////////////////////// mraidbridge.windowLoaded = false; window.addEventListener(‘load’, function(e) { mraidbridge.windowLoaded = true }); mraidbridge.fireReadyEvent = function() { mraidbridge.fireEvent(‘ready’); }; mraidbridge.fireChangeEvent = function(properties) { mraidbridge.fireEvent(‘change’, properties); }; mraidbridge.fireErrorEvent = function(message, action) { mraidbridge.fireEvent(‘error’, message, action); }; mraidbridge.fireEvent = function(type) { console.log(“mraidBridge: firing event of type: ” + type); var ls = listeners[type]; if (ls) { var args = Array.prototype.slice.call(arguments); args.shift(); var l = ls.length; for (var i = 0; i < l; i++) { ls[i].apply(null, args); } } }; mraidbridge.nativeCallComplete = function(command) { console.log(“native Call complete: ” + command); if (nativeCallQueue.length === 0) { nativeCallInFlight = false; return; } var nextCall = nativeCallQueue.pop(); window.location = nextCall; }; mraidbridge.executeNativeCall = function(command) { if (!mraidbridge.windowLoaded) { console.log(“rejecting native call, window onload has not been invoked”); return; } var call = ‘mraid://’ + command; var key, value; var isFirstArgument = true; for (var i = 1; i < arguments.length; i += 2) { key = arguments[i]; value = arguments[i + 1]; if (value === null) continue; if (isFirstArgument) { call += ‘?’; isFirstArgument = false; } else { call += ‘&’; } call += encodeURIComponent(key) + ‘=’ + encodeURIComponent(value); } if (nativeCallInFlight) { nativeCallQueue.push(call); } else { nativeCallInFlight = true; window.location = call; } }; ////////////////////////////////////////////////////////////////////////////////////////////////// mraidbridge.addEventListener = function(event, listener) { var eventListeners; listeners[event] = listeners[event] || []; eventListeners = listeners[event]; for (var l in eventListeners) { // LoadListener already registered, so no need to add it. if (listener === l) return; } eventListeners.push(listener); }; mraidbridge.removeEventListener = function(event, listener) { if (listeners.hasOwnProperty(event)) { var eventListeners = listeners[event]; if (eventListeners) { var idx = eventListeners.indexOf(listener); if (idx !== -1) { eventListeners.splice(idx, 1); } } } }; }()); (function() { var mraid = window.mraid = {}; var bridge = window.mraidbridge; // Constants. //////////////////////////////////////////////////////////////////////////////////// var VERSION = mraid.VERSION = ‘2.0’; var STATES = mraid.STATES = { LOADING: ‘loading’, // Initial state. DEFAULT: ‘default’, EXPANDED: ‘expanded’, HIDDEN: ‘hidden’, RESIZED: ‘resized’ }; var EVENTS = mraid.EVENTS = { ERROR: ‘error’, INFO: ‘info’, READY: ‘ready’, STATECHANGE: ‘stateChange’, VIEWABLECHANGE: ‘viewableChange’, SIZECHANGE: ‘sizeChange’ }; var PLACEMENT_TYPES = mraid.PLACEMENT_TYPES = { UNKNOWN: ‘unknown’, INLINE: ‘inline’, INTERSTITIAL: ‘interstitial’ }; // External MRAID state: may be directly or indirectly modified by the ad JS. //////////////////// // Properties which define the behavior of an expandable ad. var expandProperties = { width: -1, height: -1, useCustomClose: false, isModal: true, lockOrientation: false }; var hasSetCustomSize = false; var hasSetCreativeSize = false; var hasSetCreativeOffset = false; var hasSetCustomClose = false; var listeners = {}; // Internal MRAID state. Modified by the native SDK. ///////////////////////////////////////////// var state = STATES.LOADING; var isViewable = false; var screenSize = { width: -1, height: -1 }; var maxSize = { width: -1, height: -1 }; var adSize = { width: -1, height: -1 }; var currentPosition = { x:0, y:0, width:0, height:0 }; var mraidDefaultPosition = { x:0, y:0, width:0, height:0 }; // Properties which define the behavior of an resized ad. var resizeProperties = { width:-1, height:-1, customClosePosition:’top-right’,

ckeditor 4 CDN specify file type on upload button

I’m trying to specify ckeditor 4 input type file and specify img file on input type file. But I can not modify it since it’s created by the plugin.

So I’m trying to add those attribute, but it’s not working, I have a lot of mistake, I thunk my selectror are wrongs

I’m calling this code on ready function so I’m sure the ckeditor form is fully loaded when I call it

$('#cke_126_fileInput_input').attr('accept', 'image/png, image/jpeg');

the form of ckeditor contains this input

    <form enctype="multipart/form-data" method="POST" dir="ltr" lang="fr" action="/uploader/upload.php?CKEditor=msg-area&amp;CKEditorFuncNum=1&amp;langCode=fr">
<label id="cke_125_label" for="cke_126_fileInput_input" style="display:none">Envoyer sur le serveur</label><input style="width:100%" id="cke_126_fileInput_input" aria-labelledby="cke_125_label" type="file" name="upload" size="38"></form>

I don’t know how to force this.

Anykind of help would be much appreciated

Horizontal scroll slider – instagram storys slider

I’m trying to make an Instagram story, but I’m having trouble even though everything is correct in javascript, can you help?

HTML

<!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>HTML</title>
    <link rel="stylesheet" href="./style.css">
    <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>

</head>
<body>
    <div class="container">
        <div class="horizontal-scroll">
            <button class="btn-scroll" id="btn-scroll-left" onclick="scrollHorizontally(1)" ><i  class="fas fa-chevron-left"></i></button>
            <button class="btn-scroll" id="btn-scroll-right" onclick="scrollHorizontally(-1)"  ><i  class="fas fa-chevron-right"></i></button>
            <div class="storys-container">
                <div class="story-circle"><img src="./img/face/1.jfif "></div>
                <div class="story-circle"><img src="./img/face/2.jfif "></div>
                <div class="story-circle"><img src="./img/face/3.jfif "></div>
                <div class="story-circle"><img src="./img/face/4.jfif "></div>
                <div class="story-circle"><img src="./img/face/5.jfif "></div>
                <div class="story-circle"><img src="./img/face/6.jfif "></div>
                <div class="story-circle"><img src="./img/face/7.jfif "></div>
                <div class="story-circle"><img src="./img/face/8.jfif "></div>
                <div class="story-circle"><img src="./img/face/9.jfif "></div>

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

css

body{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

.container{
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f9f9f9;
    height: 100vh;
}

.horizontal-scroll{
    width: 600px;
    height: 80px;
    background-color: #fff;
    border: 1px solid #ddd;
    border-radius: 5px;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    position: relative;
    overflow: hidden;
}


.horizontal-scroll .btn-scroll{
    background-color: #fff;
    color: #999;
    box-shadow: 0 0 10px #999;
    padding: 5px 8px;
    border: 0;
    border-radius: 50%;
    margin: 0 5px;
    z-index: 1;
    cursor: pointer;
    transition: 1s;
}



.storys-container{
    display: flex;
    flex-direction: row;;
    justify-content: flex-start;
    align-items: center;
    position: absolute;
    left: 0;
    transition: 0.5s all ease-out;
}

.story-circle{
    background: linear-gradient(rgb(231,0,231),rgb(255,115,0));
    width: 60px;
    height: 60px;
    margin: 15px 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 50%;

}

.story-circle img{
    width: 52px;
    height: 52px;
    border-radius: 50%;
    border: 2px solid #fff;



}






javascript

        let currentScroolPosition = 0;
        let scroolAmount = 320;

        const sCont = document.querySelector(".storys-container")
        const hScroll = document.querySelector(".horizontal-scroll")
        const btnScrollLeft = document.querySelector("#btn-scroll-left")
        const btnScrollRight = document.querySelector("#btn-scroll-right")


        btnScrollLeft.style.opacity = "0"


        let maxScroll = -sCont.offsetWidth + hScroll.offsetWidth;

        function scrollHorizontally(val){
            currentScroolPosition += ( val * scrollAmount );

            if(currentScroolPosition > 0){
                currentScroolPosition = 0;
                btnScrollLeft.style.opacity = "0"
            }else{
                btnScrollLeft.style.opacity = "1"

            }

            if(currentScroolPosition <= maxScroll){
                currentScroolPosition = maxScroll;
                btnScrollRight.style.opacity = "0"
            }else{
                btnScrollRight.style.opacity = "1"

            }


            sCont.style.left = currentScroolPosition + "px";
        }

I’m waiting for your answers, I couldn’t solve this problem for hours

Here is the video of the friend who made it. everything is correct but it’s not working for me either.
https://www.youtube.com/watch?v=LFVFxDXQxxE&ab_channel=Fullstack4Dev

Getting the first property from javascript object

I’m trying to get the first properties from the javascript objects. were I’m fetching data from the third-party library with multiple objects that have the same object name(CountryName:) and different first property names(USA, Portugal, Ghana, etc). so I’m trying to get all the first properties at the same time and reuse them in my DOM

Discord – Add image from Google Drive in Embed Message

I have a list of files that I’m retrieving from Drive:

const list = await drive.files.list({
  q: `parents in '${process.env.DRIVE_DIR}' and name contains 'test_'`,
  spaces: 'drive',
  fields: 'files(id, mimeType, webViewLink)'
})

After getting the files I want to send embed messages with the image from Drive:

const embed = new MessageEmbed()
  .setColor('#6adada')
  .setTitle('Test')
  .setImage(list.data.files[index].webViewLink)
message.channel.send({embeds: })

I checked all permission on Google Drive and they are correct, if I access the link as a guest I can see the image in the browser. Is there something that I’m missing? Thanks in advance.

can’t fetch msgraph data using vanilla js

I am trying to pull data from the endpoint https://graph.microsoft.com/v1.0/me/. I have done this using python but I can’t seem to fetch data from Microsoft Graph using vanilla js.

When I attempt to perform a fetch request. I get a 200 response but nothing is inside the response object.

Here is the fetch code:

fetch("https://graph.microsoft.com/v1.0/me/", {
  method: "GET",
  "headers": {
    "authorization": "Bearer ENTERTOKENHERE"}
}).then(data =>{console.log(data)});

I get a response of:

Response {type: 'cors', url: 'https://graph.microsoft.com/v1.0/me/', redirected: false, status: 200, ok: true, …}

but I am expecting more of a response like the one I get from the https://developer.microsoft.com/en-us/graph/graph-explorer website like this:

{
    "@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users/$entity",
    "businessPhones": [],
    "displayName": "Edd Bighead",
    "givenName": "Edd",
    "jobTitle": null,
    "mail": "[email protected]",
    "mobilePhone": null,
    "officeLocation": null,
    "preferredLanguage": "en-US",
    "surname": "Bighead",
    "userPrincipalName": "[email protected]",
    "id": "2fa321d9-bda3-41c1-8be8-5d4049ed8765"
}

Is there anything I am missing to get the data from msgraph using vanilla js only?

Insert text by its index in javascript

So I wrote a code where there are 5 true/false questions and after clicking on the check button, the program shows whether your answer was in/correct by making the question box red or green and displays your score.

But after the click, it should also display each justification below the true/false buttons which is in questions as justif. I have written <p id = "just${(index+1)}"></p> so that I can display justifications by index easily, but I don’t quite get how to do so

I have tried with getElementById and insertAdjacentHTML but no luck, can somebody tell me how to write that part of the code?

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

<head>
  <title>Template</title>
  <link rel="stylesheet" href="style.css">
  <script>
    let questions = [{
      "quest": "'Visibility' is CSS property that specifies the transparency",
      "ans": false,
      "justif": "'Opacity' is used to specify the transparency of an element whereas 'visibility' specifies if element is visible "
    }, {
      "quest": "HTML elements can have 'id' and 'class' at the same time",
      "ans": true,
      "justif": "Any HTML element can have both of them together"
    }, {
      "quest": "DIV technically stands for Container",
      "ans": false,
      "justif": "DIV stands for Division"
    }, {
      "quest": "Padding can be negative",
      "ans": false,
      "justif": "Values for padding values can only be positive or zero"
    }, {
      "quest": "'text-shadow' is the CSS property which adds shadows to the text",
      "ans": true,
      "justif": "The CSS 'text-shadow' is used to add shadows to the text"
    }];
    console.log(questions[0].quest);
  </script>
</head>

<body>
  <section id="main">

  </section>
  <p id="score"></p>
  <button type="button" onclick="checkAnswers()"><b>Check</b></button>
  <script>
    let i = 1;
    questions.forEach(function(item, index) {
      let HTMLcode = `<form id="id${(index+1)}">
            <p>${item.quest}</p>
            <input type="radio" name = "q${(index+1)}" id="q${(index+1)}t" value="1">
            <label class = "true" for="q${(index+1)}t">True</label>
            <input type="radio" name = "q${(index+1)}" id="q${(index+1)}f" value="0">
            <label class = "false" for="q${(index+1)}f">False</label>
            <p id = "just${(index+1)}"></p>
        </form>
        `;
      document.getElementById('main').insertAdjacentHTML('beforeend', HTMLcode);
      i++;
    });

    function checkAnswers() {
      let correctAnswered = 0;
      document.querySelectorAll('input[type="radio"]:checked').forEach(function(radio) {
        let radioId = parseInt(radio.id.substring(1));
        let userAnswer = radio.id.substring(1).slice(-1);
        let questionAnswer = questions[radioId - 1].ans;
        let p = document.getElementById("id" + radioId);
        if (userAnswer == 't' && questionAnswer == true ||
          userAnswer == 'f' && questionAnswer == false) {
          p.style.backgroundColor = 'rgba(34, 172, 0, 0.789)';
          correctAnswered++;
        } else {
          p.style.backgroundColor = 'rgba(255, 0, 0, 0.789)';
        }
      });
      let score = document.getElementById("score");
      score.textContent = "Your Score is " + correctAnswered + " out of 5";
    }
  </script>
</body>

</html>

ENOENT error on xml2js but file did exists

const xml2js = require('xml2js');
const fs = require('fs');

fs.readFile('https://www.tcmb.gov.tr/kurlar/today.xml', (err, data) => {
    if(err) console.log(err);
    var data = data.toString().replace("ufeff", "");
    xml2js.parseStringPromise(data, (err, res) => {
        if(err){
            console.log(err);
        } else {
            console.log(res);
        }
    });
});

This is my code in nodejs I try to get data on a https link with xml2js first by using the way it says in the npm page pf xml2js it gives some error and when I chechk on web I find solution of using with fs but still geting this error enter image description here

I know the directory exists because if you go to link used in code it shows something but in code just gives error if someone can help I will be very happy

How to insert an element in multidimentional array in Javascript [closed]

I want to create the bellow array from user inputs:

myArr = [
    parantArr1[
        childArr1[
            'user input1'
            'user input2'
        ],
        childArr2[],
        .....
     ],
     parantArr2[
         .....
     ]
]

My code is as bellow:

myArr=[];
myArr.push(new Array('parant1'));
myArr.push(new Array('parant2'));
myArr[0].push(new Array('child1'));
myArr[1].push(new Array('child2'));

myArr[0][0].push('user input1');
myArr[0][1].push('user input2');

Why the code is not working?
The out put is

myArr[[parant1,[child1]],[parent2,]]

Delete elements that have intersected the viewport

I am playing around with intersection observer to create an infinite scroll dog website. As you scroll and 6 dogs appear, an api fires off 6 more times to grab more dogs to add to the DOM. I would like for the dogs to load in as a user scrolls but as an already viewed dog leaves the viewport and goes up on the page, that element is then deleted off the page. SO the dogs always load in scrolling down, but scrolling up you are always at the top of the page. My current implementation in the function called lastFunc is causing it to act really weird. How can I achieve the desired effect.

class CardGenerator {
  constructor() {
    this.$cardContainer = document.querySelector('.card-container');
    this.$allCards = undefined;

    this.observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          entry.target.classList.toggle('show', entry.isIntersecting);
          if (entry.isIntersecting) {
            this.observer.unobserve(entry.target);
          }
        });
      },
      {
        threshold: 1,
        rootMargin: '150px',
      }
    );
    this.loadNewCards();
  }

  cacheDOMElements() {
    this.$allCards = document.querySelectorAll('.card');
  }

  loadNewCards() {
    for (let index = 0; index < 6; index++) {
      fetch('https://dog.ceo/api/breeds/image/random', { method: 'GET' })
        .then((result) => {
          return result.json();
        })
        .then((r) => {
          console.log(r);
          const card = document.createElement('div');
          card.classList.add('card');

          const imageElement = document.createElement('img');
          imageElement.classList.add('forza-img');

          imageElement.setAttribute('src', r.message);
          card.appendChild(imageElement);
          this.observer.observe(card);
          this.$cardContainer.append(card);
          this.cacheDOMElements();
          if (this.$allCards.length % 6 === 0) this.lastFunc();
        });
    }
  }

  lastFunc() {
    console.log(this.$allCards);
    if (this.$allCards.length > 12) {
      this.$allCards.forEach((item, idx) => {
        if (idx < 6) {
          item.remove();
        }
      });
    }

    this.$allCards.forEach((card, idx) => {
      this.observer.observe(card);
    });

    const lastCardObserver = new IntersectionObserver((entries) => {
      const $lastCard = entries[0];
      if (!$lastCard.isIntersecting) return;
      this.loadNewCards();
      lastCardObserver.unobserve($lastCard.target);
    });

    lastCardObserver.observe(document.querySelector('.card:last-child'));
  }
}

const cardGenerator = new CardGenerator();
html,
body {
  height: 100%;
  width: 100%;
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

.card {
  float: left;
  width: 48vw;
  margin: 1%;
  transform: translateX(100px);
  opacity: 0;
  transition: 150ms;
}

.card.show {
  transform: translateY(0);
  opacity: 1;
}

.card img {
  width: 100%;
  border-radius: 15px;
  height: 30vh;
  object-fit: cover;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <h1>Dog Random Images</h1>
  <div class="card-container"></div>
</body>

<script src="app.js" ></script>
</html>

How do i get input from website with node and after send it to database

I am haveing problem with getting input from my website send it so node (server.js) and the value to database. I already have done database connection and it works but value of input was undefined, so i have found out that i dont know how to get the input from the webpage (store.ejs).
So if someone could help.
“I am making eshop for my self”.

store.ejs

<!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>Store</title>
    <link rel="shortcut icon" type="image/x-icon" href="/images/logo.png" />
    <link rel="stylesheet" href="style.css">
    <script src="https://checkout.stripe.com/checkout.js" defer></script>
    <script>
      var stripePublicKey = '<%= stripePublicKey %>'
    </script>
<script src="script.js" defer></script>
<!--<script src="../billing.js" defer></script>-->








<link rel="icon" href="/images/logo.png">
</head>
<body>
<!--  <a href="cart.html"><img src="cart-logo.png" id="cart-logo" style="background-color: #eee;border-radius: 50%;"></a> -->
    <span id="logo2">
        <a href="index.html"><img src="/images/logo.png" style="border-radius: 50%; width: 100px; position: relative; right: 0%; left: 50%;"></a>
        </span>
  <div id="navigator1">
  <nav>
    <ul>
      <li><a href='store'>Store</a></li>
      <li><a href="aboutus.html"> About us</a></li>
      <!--<li><a href='tshirtjacket.html'></a></li>-->
      <!--<li><a href='other.html'></a></li>-->
      <!--<li><a href=''>Other</a></li>-->
      <!--<li><a href=''>Other</a></li>-->
      <div class="img2">
        <li><a href="https://www.instagram.com/bonekicks/"><img src="/images/instagram-logo.png" id="img2"></a></li>
        </div>
  </ul>
</nav>
<div id="navigator1"></div>
<section class="container content-section">
<h1 style="text-align: center;">Store</h1>
<br>
<div></div>
<div class="shop-items">
    <% items.boot.forEach(function(item){ %>
        <div class="shop-item" data-item-id="<%= item.id %>">
            <span class="shop-item-title"><%= item.name %></span>
            <img class="shop-item-image" src="/images/<%= item.imgName %>">
            <div class="shop-item-details">
                <span class="shop-item-price">$<%= item.price / 100 %></span>
                <span class=""><%= item.quantity%> in stock</span>
                <button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
            </div>
        </div>
    <% }) %> 
  
  </div>
</div>
</section>

<section class="container content-section">
<h2 class="section-header">CART</h2>
<div class="cart-row">
  <span class="cart-item cart-header cart-column">ITEM</span>
  <span class="cart-price cart-header cart-column">PRICE</span>
  <span class="cart-quantity cart-header cart-column">QUANTITY</span>
</div>
<div class="cart-items">
</div>
<div class="cart-total">
  <strong class="cart-total-title">Total</strong>
  <span class="cart-total-price">$0</span>
</div>

<form action="../server.js" method="POST" id="billing">
  <div class="form-group" id="billing1">
    <label for="state"><!--State--></label>
    <input type="text" id="state" placeholder="State: " name="state">
  </div>
  <div class="form-group">
    <label for="address"><!--Address--></label>
    <input type="text" id="address" placeholder="Address: " name="address">
  </div>
  <div class="form-group">
    <label for="exampleInputEmail1"><!--Zip code--></label>
    <input type="text" id="zip" name="zip" placeholder="Zip code: ">
  </div>        
 



<button class="btn btn-primary btn-purchase" onclick="clicked()" type="button">PURCHASE</button>
</form>
</section>

</body>
</html>

server.js

    require('dotenv').config()
}

const stripeSecretKey = process.env.STRIPE_SECRET_KEY
const stripePublicKey = process.env.STRIPE_PUBLIC_KEY

//console.log(stripeSecretKey, stripePublicKey)

const express = require('express')
const app = express()
const fs = require('fs')
const stripe = require('stripe')(stripeSecretKey)




var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var flash = require('express-flash');
var session = require('express-session');
var mysql = require('mysql');
var http = require('http'); 





app.set('view engine', 'ejs')

app.set('views', path.join(__dirname, 'views'));

app.use(express.json())
app.use(express.static('public'))
app.use(logger('dev'));
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({ 
    secret: '123456catr',
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: 60000 }
}))
 
app.use(flash());










var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "bonekicks"
  });
  
  
  
   

    










app.get('/store', function(req, res) {
    fs.readFile('items.json', function(error, data) {
        if (error) {
            res.status(500).end()
        } else {
            res.render('store.ejs', {
                stripePublicKey: stripePublicKey,
                items: JSON.parse(data)
            })
            
            
    



        }
    })
})


app.post('/purchase', function(req, res) {
    fs.readFile('items.json', function(error, data) {
        if (error) {
            res.status(500).end()
        } else {
            const itemsJson = JSON.parse(data)
            const itemsArray = itemsJson.boot
            let total = 0
            
            
            
            
            req.body.items.forEach(function(item){
                const itemJson = itemsArray.find(function(a){
                    return a.id == item.id
                    
                })
                total = total + itemJson.price * item.quantity
                console.log(Date())
                console.log("id of product: " + itemJson.id + "; quantity: " + item.quantity + " "+ total)
               
                console.log("//////////////////////////////////////////////////////////////////////////////////")
                
            })
  


            stripe.charges.create({
                amount: total,
                source: req.body.stripeTokenId,
                currency: 'usd',
                
                

            }).then(function(){
                console.log('Charge Succesful')
                res.json({message: 'Successfully purchased items ;)'})
                
               
                
                var state1 = req.body.state;
                var address = req.body.address;
                var zip = req.body.zip;
               var state;
             



             


           

                con.connect(function(err) {
                    if (err) throw err;
                    

                    var sql = `INSERT INTO customers (c_state, c_address, c_zip) VALUES ("${state1}", "${address}", "${zip}")`;
                    con.query(sql, function (err, result) {
                      if (err) throw err;
                      
                      console.log("1 record inserted, ID: " + result.insertId);
                      //console.log(state + " " + address + " " + zip);
                    });
                  });
                  
                
          
                


                
                

                  
            
            }).catch(function(){
                console.log('Charge Fail')
                res.status(500).end()
            })
            
            

            



        }
    })
})

  

app.listen(3000)```


and script.js whitch is used by store.ejs


and script.js whitch is used by store.ejs




if (document.readyState == 'loading') {
    document.addEventListener('DOMContentLoaded', ready)
} else {
    ready()
}



function ready() {
    var removeCartItemButtons = document.getElementsByClassName('btn-danger')
    for (var i = 0; i < removeCartItemButtons.length; i++) {
        var button = removeCartItemButtons[i]
        button.addEventListener('click', removeCartItem)
    }
    
    var quantityInputs = document.getElementsByClassName('cart-quantity-input')
    for (var i = 0; i < quantityInputs.length; i++) {
        var input = quantityInputs[i]
        input.addEventListener('change', quantityChanged)
    }

    var addToCartButtons = document.getElementsByClassName('shop-item-button')
    for (var i = 0; i < addToCartButtons.length; i++) {
        var button = addToCartButtons[i]
        button.addEventListener('click', addToCartClicked)
    }

    document.getElementsByClassName('btn-purchase')[0].addEventListener('click', purchaseClicked)
}



var stripeHandler = StripeCheckout.configure({
    key: stripePublicKey,
    locale: 'auto',
    token: function(token) {
        var items = []
        var cartItemContainer = document.getElementsByClassName('cart-items')[0]
        var cartRows = cartItemContainer.getElementsByClassName('cart-row')
        for (var a = 0; a < cartRows.length; a++) {
            var cartRow = cartRows[a]
            var quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0]
            var quantity = quantityElement.value
            var id = cartRow.dataset.itemId
            items.push({
                id: id,
                quantity: quantity
            })
        }

        fetch('/purchase', {
            method: 'POST', 
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            body: JSON.stringify({
                stripeTokenId: token.id,
                items: items
            })
        }).then(function(res){
            return res.json()
        }).then(function(data){
            alert(data.message)
            var cartItems = document.getElementsByClassName('cart-items')[0]
            while (cartItems.hasChildNodes()) {
                cartItems.removeChild(cartItems.firstChild)
            }
            updateCartTotal()
        }).catch(function(error){
            console.error(error)
        })
    }
})


function purchaseClicked() {
    
    var priceElement = document.getElementsByClassName('cart-total-price')[0]
    var price = parseFloat(priceElement.innerText.replace('$', '')) * 100
    stripeHandler.open({
        amount: price
    })

    
    

    
}

function removeCartItem(event) {
    var buttonClicked = event.target
    buttonClicked.parentElement.parentElement.remove()
    updateCartTotal()
}

function quantityChanged(event) {
    var input = event.target
    if (isNaN(input.value) || input.value <= 0) {
        input.value = 1
    }
    updateCartTotal()
}

function addToCartClicked(event) {
    var button = event.target
    var shopItem = button.parentElement.parentElement
    var title = shopItem.getElementsByClassName('shop-item-title')[0].innerText
    var price = shopItem.getElementsByClassName('shop-item-price')[0].innerText
    var imageSrc = shopItem.getElementsByClassName('shop-item-image')[0].src
    var id = shopItem.dataset.itemId
    addItemToCart(title, price, imageSrc, id)
    updateCartTotal()
}

function addItemToCart(title, price, imageSrc, id) {
    var cartRow = document.createElement('div')
    cartRow.classList.add('cart-row')
    cartRow.dataset.itemId = id
    var cartItems = document.getElementsByClassName('cart-items')[0]
    var cartItemNames = cartItems.getElementsByClassName('cart-item-title')
    for (var i = 0; i < cartItemNames.length; i++) {
        if (cartItemNames[i].innerText == title) {
            alert('This item is already added to the cart')
            return
        }
    }
    var cartRowContents = `
        <div class="cart-item cart-column">
            <img class="cart-item-image" src="${imageSrc}" width="100" height="100">
            <span class="cart-item-title">${title}</span>
        </div>
        <span class="cart-price cart-column">${price}</span>
        <div class="cart-quantity cart-column">
            <input class="cart-quantity-input" type="number" value="1">
            <button class="btn btn-danger" type="button">REMOVE</button>
        </div>`
    cartRow.innerHTML = cartRowContents
    cartItems.append(cartRow)
    cartRow.getElementsByClassName('btn-danger')[0].addEventListener('click', removeCartItem)
    cartRow.getElementsByClassName('cart-quantity-input')[0].addEventListener('change', quantityChanged)
}

function updateCartTotal() {
    var cartItemContainer = document.getElementsByClassName('cart-items')[0]
    var cartRows = cartItemContainer.getElementsByClassName('cart-row')
    var total = 0
    for (var i = 0; i < cartRows.length; i++) {
        var cartRow = cartRows[i]
        var priceElement = cartRow.getElementsByClassName('cart-price')[0]
        var quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0]
        var price = parseFloat(priceElement.innerText.replace('$', ''))
        var quantity = quantityElement.value
        total = total + (price * quantity)
    }
    total = Math.round(total * 100) / 100
    document.getElementsByClassName('cart-total-price')[0].innerText = '$' + total
}





Image of directory tree – If needed

REST API Post body from XML endpoint URL

I am trying to make a post request to a server(https://exampleapi.com/echo/post/xml) and I have a piece of code that sort of works. What I want to achieve is to have the XML load from the URL https://randomuser.me/api/?format=xml rather than the XML contained in the backticks.
Below is my code sample:

var url = "https://exampleapi.com/echo/post/xml";

var xhr = new XMLHttpRequest();
xhr.open("POST", url);

xhr.setRequestHeader("Content-Type", "application/xml");
xhr.setRequestHeader("Accept", "application/xml");

xhr.onreadystatechange = function () {
  if (xhr.readyState === 4) {
    console.log(xhr.status);
    console.log(xhr.responseText);
  }
};

var data = `<user>
<results>
<gender>male</gender>
<name>
<title>Mr</title>
<first>Jasper</first>
<last>Smith</last>
</name>
<location>
<street>
<number>1966</number>
<name>Chatham Road</name>
</street>
<city>Dunedin</city>
<state>Canterbury</state>
<country>New Zealand</country>
<postcode>63789</postcode>
<coordinates>
<latitude>66.6618</latitude>
<longitude>-110.4640</longitude>
</coordinates>
<timezone>
<offset>-10:00</offset>
<description>Hawaii</description>
</timezone>
</location>
<email>[email protected]</email>
<login>
<uuid>8a132229-407b-47db-9a03-73c5d6c8c969</uuid>
<username>angryelephant526</username>
<password>nicole1</password>
<salt>saEREYSt</salt>
<md5>4292d6c17f10dad0224746c16f510032</md5>
<sha1>43d82fdd05fe62edcec774d534aaa41dde6c32dd</sha1>
<sha256>891f6c6f1193b59d70fd61c482575c9c04fa951123ec081e459b2a46235e1694</sha256>
</login>
<dob>
<date>1955-01-13T12:46:36.403Z</date>
<age>66</age>
</dob>
<registered>
<date>2015-08-05T20:56:20.380Z</date>
<age>6</age>
</registered>
<phone>(847)-575-4692</phone>
<cell>(051)-964-8266</cell>
<id>
<name/>
<value/>
</id>
<picture>
<large>https://randomuser.me/api/portraits/men/34.jpg</large>
<medium>https://randomuser.me/api/portraits/med/men/34.jpg</medium>
<thumbnail>https://randomuser.me/api/portraits/thumb/men/34.jpg</thumbnail>
</picture>
<nat>NZ</nat>
</results>
<info>
<seed>9dca58235eff2b2b</seed>
<results>1</results>
<page>1</page>
<version>1.3</version>
</info>
</user>`;

xhr.send(data);```

ReactJS onClick event not work in Google Chrome for option tag

In ReactJS, onClick event does not work in Google Chrome browser but works fine in Firefox. When I add onClick event with arrow function in option tag inside select it’s not work in any situation in Google Chrome.

<select>
   {data.map( (item) => {                            
     return(
       <>
         <option onClick={()=>alert('Test')} value={item.name} key={item.id}>{item.name}</option>
       </>
      )
   })}
</select>

I actually need to call an ES6 arrow function with some parameter inside option tag

<select>
{data.map( (item) => {
  return(
     <>
      <option onClick={()=>LoadNew(item.id)} value={item.name} key={item.id}>{item.name}</option>
     </>
    )
  })}
</select>

This is working fine in Firefox but doesn’t work in the Google Chrome browser. Any idea how can I solve this problem?