Add Hubspot from Script to custom website and load it on click

I’m trying to use the following code:

<script charset="utf-8" type="text/javascript" src="//js-eu1.hsforms.net/forms/embed/v2.js"></script>
        <script>
          hbspt.forms.create({
            region: "eu1",
            portalId: "26913186",
            formId: "a106c8d3-ab30-4bdc-83d0-55d8874bd351"
          });
        </script>

The problem I have is: I use a “form window” – the user first click on a “contact button” and then an adaptive modal appears – the code for now is the following that is printed with js to the modal ( you can also check it live on ( https:wdsa.gr ) :

const contactHtml = `<div id="" class="formcontainer"><div class="contactformicons"><a href="tel:+302113332578" class=""><img class="ct" src="/media/icons/wdsa_agency_icons_telephone.svg" alt="Γραφιστικά στοιχεία της WDSA - Ανάπτυξη ιστοσελίδων και λογισμικού"></a><a rel="nofollow" target=”_blank” href="https://meetings-eu1.hubspot.com/konstantinos-anastasiades" class="calbtn"><img src="/media/icons/wdsa_appointment-calendar.svg" alt="Γραφιστικά στοιχεία της WDSA - Ανάπτυξη ιστοσελίδων και λογισμικού"></a></div><hr><form action="" class="contactform"><div class="nameinputs"><input disabled placeholder="Όνομα" name="firstname" type="text" class="name inputdesignmain"><input disabled placeholder="Επίθετο" name="lastname" type="text" class="surname inputdesignmain"></div><input placeholder="Τηλέφωνο" disabled name="phone" type="tel" class="tel inputdesignmain"><input disabled placeholder="Email" name="email" type="text" class="email inputdesignmain"><input disabled placeholder="Επάγγελμα/Εταιρία" name="company" type="text" class="profession inputdesignmain"><textarea placeholder="Γράψτε το μήνυμα σας εδώ.." class="Message inputdesignmain" name="message" id="" disabled cols="30" rows="10"></textarea><input style="font-size:1.2rem; margin-top:.4em;" disabled type="submit" class="sendrequest" value="Αποστολή"></form></div></div>`

What I’ve tried yet to do is the following code, replace the custom form with Hubspot’s embed script – But when I do it that way, the form does not load:

const contactHtml = `<div id="" class="formcontainer"><div class="contactformicons"><a href="tel:+302113332578" class=""><img class="ct" src="/media/icons/wdsa_agency_icons_telephone.svg" alt="Γραφιστικά στοιχεία της WDSA - Ανάπτυξη ιστοσελίδων και λογισμικού"></a><a rel="nofollow" target=”_blank” href="https://meetings-eu1.hubspot.com/konstantinos-anastasiades" class="calbtn"><img src="/media/icons/wdsa_appointment-calendar.svg" alt="Γραφιστικά στοιχεία της WDSA - Ανάπτυξη ιστοσελίδων και λογισμικού"></a></div><hr><script charset="utf-8" type="text/javascript" src="//js-eu1.hsforms.net/forms/embed/v2.js"></script>
<script>
  hbspt.forms.create({
    region: "eu1",
    portalId: "26913186",
    formId: "a106c8d3-ab30-4bdc-83d0-55d8874bd351"
  });
</script></div></div>`

How do I return the route from method

I currently have the following method that recursively searches for a particular route.

    this.iterate(this.rootRoutes, routeHeirarchy, 0);

    public iterate(route: any, routeHeirarchy: string[], startIndex: number) {
        const selectedRoute = null;
        if (route.path === routeHeirarchy[startIndex] && startIndex === routeHeirarchy.length - 1) {
          selectedRoute = { 
            route,
            path: (!route.data) ? route.path : route.data.tabdata.request.path
          };
          return;
        } else {
          if (route.children) {
            if (route.children.length > 0) {
              route.children.forEach((route: any) => {
                this.iterate(route, routeHeirarchy, startIndex + 1);
              });
            }
          }
        }
      }

Could someone please refactor it to improve the code and return the route, without causing an error.

What is the Unique ID for the Library for Plaid in Google Apps Script?

I am getting back errors that Plaid is not defined in Apps Script while integrating Plaid into Google Sheets. ChatGPT told me to add the Plaid library using the unique ID found in the docs, but I’ve looked everywhere and can’t find it. Does anyone know where I could find this?

I tried running the code and expected it to work but got back an error… my guess is that I need to install the Plaid library but I’m not sure.

I write a removeeventlistener on a button but it isn t working

We have a button “dice1” that .onclick generates a ramdom img of a dice’s face.

So, i need to remove that event (removing the img it builds) clicking on another button “var clearButton”, but when I click on it nothing happens.

here’s the JS code:

    dice1.addEventListener("click", img);
    function img(){
        
        count++;
        if( count == 1 ) {
                if(ramdom == 1){
                var img1 = document.createElement("img");               
                img1.src = "https://i.ibb.co/HPHsSHp/d1.jpg"; 
                img1.classList.add("Upload");
                var src = document.getElementById("img1");     
                src.appendChild(img1); 
                document.getElementById("img1").className = "position"; 
            }else if(ramdom == 2){
                var img2 = document.createElement("img");
                img2.src = "https://i.ibb.co/ZXmCQxD/d2.jpg";
                img2.classList.add("Upload");
                var src = document.getElementById("img2");
                src.appendChild(img2);
                document.getElementById("img2").className = "position";        
            }else if(ramdom == 3) {
                var img3 = document.createElement("img");   
                img3.src = "https://i.ibb.co/Y0x8K65/d3.jpg"; 
                img3.classList.add("Upload");
                var src3 = document.getElementById("img3");     
                src3.appendChild(img3); 
                document.getElementById("img3").className = "position";
            }else if(ramdom == 4){
                var img4 = document.createElement("img");   
                img4.src = "https://i.ibb.co/8gq6Rfx/d4.jpg"; 
                img4.classList.add("Upload");
                var src = document.getElementById("img4");     
                src.appendChild(img4); 
                document.getElementById("img4").className = "position";
            }else if(ramdom == 5){
                var img5 = document.createElement("img");   
                img5.src = "https://i.ibb.co/WyWjWT9/d5.jpg";
                img5.classList.add("Upload"); 
                var src = document.getElementById("img5");     
                src.appendChild(img5); 
                document.getElementById("img5").className = "position";
            }else if(ramdom === 6){                    
                var img6 = document.createElement("img");   
                img6.src = "https://i.ibb.co/zZrByy0/d6.jpg";
                img6.classList.add("Upload"); 
                var src = document.getElementById("img6");     
                src.appendChild(img6); 
                document.getElementById("img6").className = "position";
                
            }  
        
        }
        let clearButton = document.getElementById('clear');
        clearButton.removeEventListener("click", img);
    } ;

So, i need to remove that dice1.addeventlistener (removing the img it builds) clicking on another button “var clearButton”, but when I click on it nothing happens.

Need help error returing ‘0’ rather than the defined message

I have a single field form that sends a password reset email. the validation works if the user enters a correct username/email however if they enter an incorrect username/email or leave the field empty the error message is ‘0’ however it should be one of the messages stated. below is the validation code. i’m not sure what i have missed here.

function lost_pass_callback() {

    global $wpdb, $wp_hasher;

    $nonce = $_POST['nonce'];

    if ( ! wp_verify_nonce( $nonce, 'rs_user_lost_password_action' ) )
        die ( 'Security checked!');     
$user_login = $_POST['user_login'];

        $errors = new WP_Error();

        if ( empty( $user_login ) ) {
            $errors->add('empty_username', __('<strong>ERROR</strong>: Enter a username or e-mail address.'));
        } else if ( strpos( $user_login, '@' ) ) {
            $user_data = get_user_by( 'email', trim( $user_login ) );
            if ( empty( $user_data ) )
                $errors->add('invalid_email', __('<strong>ERROR</strong>: There is no user registered with that email address.'));
        } else {
            $login = trim( $user_login );
            $user_data = get_user_by('login', $login);
        }

        /**
         * Fires before errors are returned from a password reset request.
         *
         * @since 2.1.0
         * @since 4.4.0 Added the `$errors` parameter.
         *
         * @param WP_Error $errors A WP_Error object containing any errors generated
         *                         by using invalid credentials.
         */
        do_action( 'lostpassword_post', $errors );

        if ( $errors->get_error_code() )
            return $errors;

        if ( !$user_data ) {
            $errors->add('invalidcombo', __('<strong>ERROR</strong>: Invalid username or email.'));
            return $errors;
        }

if ( wp_mail( $user_email, wp_specialchars_decode( $title ), $message ) )
        $errors->add('confirm', __('Check your e-mail for the confirmation link.'), 'message');
    else
        $errors->add('could_not_sent', __('The e-mail could not be sent.') . "<br />n" . __('Possible reason: your host may have disabled the mail() function.'), 'message');


    // display error message
    if ( $errors->get_error_code() )
        echo '<p class="error">'. $errors->get_error_message( $errors->get_error_code() ) .'</p>';

Please help to fix this issue.

Try to use Langchain in my pure Javascript project but fail to compile. Module parse failed: Unexpected token (73:15)

I have a pure javacsript project and I try to import Langchain. After I npm install Langchain, I try to import langchain version OpenAI.

import { OpenAI } from "langchain/llms/openai";

However, it failed to compaile:

Failed to compile.

./node_modules/langchain/dist/llms/openai.js 73:15
Module parse failed: Unexpected token (73:15)
You may need an appropriate loader to handle this file type.
|     var _this;
|     _classCallCheck(this, OpenAI);
>     if (fields?.modelName?.startsWith("gpt-3.5-turbo") || fields?.modelName?.startsWith("gpt-4") || fields?.modelName?.startsWith("gpt-4-32k")) {
|       // eslint-disable-next-line no-constructor-return, @typescript-eslint/no-explicit-any
|       return _possibleConstructorReturn(_this, new OpenAIChat(fields, configuration));


My package.json is like this:

{
  "name": "speechless",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/react": "^11.11.1",
    "@emotion/styled": "^11.11.0",
    "@mui/material": "^5.13.6",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "aws-sdk": "^2.1363.0",
    "fs": "^0.0.1-security",
    "jwt-decode": "^3.1.2",
    "keyword-extractor": "^0.0.25",
    "langchain": "^0.0.101",
    "microsoft-cognitiveservices-speech-sdk": "^1.27.0",
    "natural": "^6.2.0",
    "openai": "^3.2.1",
    "os-browserify": "^0.3.0",
    "path-browserify": "^1.0.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-helmet": "^6.1.0",
    "react-router-dom": "^6.10.0",
    "react-scripts": "^2.1.3",
    "react-speech-recognition": "^3.10.0",
    "react-toastify": "^8.1.0",
    "sha1": "^1.1.1",
    "uti": "^7.1.1",
    "util": "^0.12.5",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "export NODE_OPTIONS=--openssl-legacy-provider && react-scripts start ",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

How can I fix this, I found Langchain is the only tool supporting input very long text to ChatGPT API, I have to use it in my javascript project. Anyone could help?

I also try to install typescript to my project, it still doesn’t work. When I do so, code can not run but output error, module can not find.

querySelector returns null even though id exists

I am using node.js and typescript to build a website. In one part of the code I am trying to acces an Element with the ID ‘likeForm’. This did not work.

This is the furthest I got:

in movies.ts:

import { JSDOM } from 'jsdom';
import * as fs from 'fs';

const html = fs.readFileSync('C:/Users/animo/OneDrive/Dokumente/svn/web anwendungen/src/server/views/movies.jade', 'utf-8');
const dom = new JSDOM(html);

const likeForm = <HTMLFormElement>dom.window.document.querySelector('#likeForm');

in movies.jade:

block append scripts
    +script('movie.js')

block append styles
    link(rel='stylesheet' href='/static/styles/views/movie.css')

block content
    h1 #{movie.title}
    section(class = 'displayAreaTrailer')
        p(class = 'paragraph')  #{movie.extract}
    div(class = 'columns')
        Section(class = 'displayAreaLeft')
            br 
            p(class = 'paragraph')  #{movie.extract}
            p(class = 'paragraph') Released: #{movie.release}
            p(class = 'paragraph') Schauspieler: #{movie.cast}
            p(class = 'paragraph') Genres: #{movie.genres}
            br
        Section(class = 'displayAreaRight')
            br
            form(id = 'likeForm' action = '#{movie.id}/like' method = 'get')
                input(type = 'submit' value = '♥')
            br

But I still getr an error: TypeError: Cannot read properties of null (reading ‘addEventListener’) when trying to add an Event Listener to likeForm.

Can someone enlighten me?

How can I sort variable array in React JS?

this question is so crucial, and it took me days, but I couldn’t solve it. so I receive an array of objects called shoppingItems that is a large array with 800 items.

each item is an object and overall data structure is like this:

[
  {ID:13242, Name:'something', color:`red`, price :150 },
  {ID:13242, Name:'something1', color:`green` , price : 200},
...
]

since the array is large, I decided to render it partially per each scroll using my custom hook. It has some optional props

import React, { useState, useEffect } from "react";

const useOptimizeListRenderPerformance = (
  largeListArray,
  additionalFn,
  FnParams,
  ApplyFilter
) => {
  const [itemsToShow, setItemsToShow] = useState(5);
  const [list, setList] = useState([]);
  const [startY, setStartY] = useState(0);
  const [activated, setActivated] = useState(false);
  const [firstCall, setFirstCall] = useState(true);

  const handleScroll = (e) => {
    if (e.deltaY > 0) {
      setItemsToShow((prev) => prev + 1);
    } else {
      setItemsToShow((prev) => (prev > 5 ? prev - 1 : prev));
    }
  };

  const handleTouchStart = (e) => {
    setStartY(e.touches[0].clientY);
  };

  const handleTouchMove = (e) => {
    const currentY = e.touches[0].clientY;
    if (currentY > startY) {
      setItemsToShow((prev) => prev + 1);
    } else {
      setItemsToShow((prev) => (prev > 5 ? prev - 1 : prev));
    }
  };

  useEffect(() => {
    if (largeListArray) {
      let updatedList = largeListArray.slice(0, itemsToShow);
      if (additionalFn) {
        updatedList = additionalFn(updatedList, ...FnParams);
      }
      ApplyFilter
        ? setList(ApplyFilter(largeListArray, FnParams))
        : setList(updatedList);
    }
  }, [largeListArray, itemsToShow, FnParams]);

  useEffect(() => {
    setActivated(true);
    setFirstCall(false);
  }, []);

  return {
    list,
    handleTouchMove,
    handleScroll,
    handleTouchStart,
    activated,
    firstCall,
  };
};

export default useOptimizeListRenderPerformance;

now at each scroll it shows 5 items. that means, 5 items at first and then 10 and 15 and so on.

this is my problem now:

I store selected items in localstorage so if user accidentally refreshes the page, they will not go away. I store the exact object in array.

now I want to bring them to the top of the array, but I can’t do it properly since the array length changes. some items stay in bottom because they are not even rendered yet at component mount.

on the other hand I use such function to bring selected items to the top and this makes problem even more terrible:

export const updateLargeArray = (largeArray, globalItems) => {
  // Short circuit: if globalItems is not present or is an empty array, return largeArray
  if (!globalItems || globalItems.length === 0) {
    return largeArray;
  }

  // Create a Set of globalItems IDs for faster lookup
  const globalItemsIds = new Set(globalItems.map((item) => item.ID));

  // Filter out items from largeArray that have matching IDs with globalItems
  const filteredLargeArray = largeArray.filter(
    (item) => !globalItemsIds.has(item.ID)
  );

  // Insert globalItems at the beginning of the filteredLargeArray
  return [...globalItems, ...filteredLargeArray];
};

large array is that huge array with 800 items and globalItems are selected items.

I tried to limit the number of what can be shown instead of this magical tricks to partially rendering the array but our customer rejected it.

javascript, Error while using class from a module : Cannot access class before initialization

I have a module file (modules.js). In addtion, script.js. I want to define a class in modules.js and then using that in script.js. I get this error in console:
‘Uncaught ReferenceError: Cannot access ‘myClass’ before initialization’.
How can I fix it?

modules.js:

export class myClass{
  constructor(name){
    this.name=name;
  }
  printHello(){
    console.log("Hello");
  }
}

script.js:

import { myClass} from "./modules.js";
var myObject=new myClass("Jacky");
myObject.printHello();

Combing two JSONs into one

I’m looping through and object and getting the data-attributes. After that I’m parsing it as a JSON.

     Object.entries(buyProductData).forEach(entry => {
            const [key, value] = entry;
            if(typeof value === 'object') {
                const data = JSON.parse(value.getAttribute('data-tracking-payload'));
                console.log(data);
            }
        });

console.log(data) returns two objects:

{pid: '9783834649867', sku: '9783834649867', name: 'Book 1}
{pid: '9683271123215', sku: '7552163721', name: 'Book 2}

My question is now how can I combine the two objects so I can have a single one that looks like this:

ec_Event : [
  {
    pid: '9783834649867', sku: '9783834649867', name: 'Book 1
  }, {
    pid: '9683271123215', sku: '7552163721', name: 'Book 2
  }
 ]

I tried let merge = {...data}, but it doesn’t seem to merge them.

Thanks!

security of implemting paypal on next.js

I recently created a project with next.js and node.js for backend.
when customers buy a product, they can pay with paypal and everything is okay but I added paypal code in my next.js project and I’m not sure if it is secure or not.

should I implement paypal on backend ? or implementing it into next.js is okay.
thank you

My website using Vite PWA sending 100+ workbox initiated requests for small js scripts when the site is upgraded to a newer version

I just migrated a react route-based code-splitting site to Vite.js with its PWA plugin. After upgrading the site to the latest version, I reloaded the page in Chrome and found that the workbox sending 100+ requests for js scripts in the background. I recognized the scripts as their names come from my react component files. This fetching only happens every time the site is upgraded and the service worker is updated and its cache is cleared:

enter image description here

enter image description here

I checked the responses of the js scripts and they were all redirected to the index.html files.

It seems that it only happens in Chrome. Firebox doesn’t have any issues.

export default defineConfig(async () => {
  return {
    plugins: [
      importToCDN(),
      VitePWA({
        base: "/",
        registerType: "prompt",
        manifest: {
          name: "xxx",
          short_name: "xxx",
          icons: xxx,
          display: "standalone",
          start_url: `xxx`,
          orientation: "portrait",
        },
      }),
      react({
        babel: {
          parserOpts: {
            plugins: ["decorators-legacy", "classProperties"],
          },
        },
        include: "**/*.{jsx,tsx}",
      }),
      viteS3(),
    ],
  };
});

React Route Code Splitting Example:

import React, { lazy, Suspense } from ‘react’;
import ReactDOM from ‘react-dom’;

const router = createBrowserRouter([
  {
    path: "/",
    element: (
       <React.Suspense>
           <Outlet />
       </React.Suspense>
    ),
    children: [
     {
        path: "/home",
        lazy: () => import("./pages/home"),
     },
     {
        path: "/about",
        lazy: () => import("./pages/about"),
     }
    ],
  },
]);


const root = createRoot(document.getElementById("container")); // createRoot(container!) if you use TypeScript
root.render(
    <RouterProvider router={router} />

);


Is it normal for the workbox/service worker to send so many requests like this every time a newer version of the site is launched?

Scroll tracking with Google Analytics 4 (GA4 Scroll Depth Tracking)

I am working on capturing some GA4 events based on page scroll.
Based on scroll position on the page I’m sending a percentage of how much of the page is viewed by user. 25%, 50%, 75% and 100%.

The logic is working fine but most of the time if page is scrolled a bit faster, the first event is fired but rest of the GA4 events are skipped.
For some reason GA4 events are taking some time to send an event and if multiple events are fired then only single event is captured by GA4.

gtag('event', `${scrolled}%`, {
    'sent_to': <ga4Id>,
    'event_category': 'milestone',
    'event_label': document.title,
    'event_value': scrolled,
    'non_interaction': true,
    'timestamp': new Date(),
  });

Any idea why this happens?
Am I missing a parameter or something?

Javascript not working in edge/firefox and Safari but on chrome it works

hello I had a problem but I can’t figure out where it comes from, I had javascript codes on my site developed with wordpress that were used to make the “menu filter element” work, I already inserted it about three months ago and everything worked, today I realized that the menu no longer works when I click on the buttons it does not change the filters as if the javascript code were no longer there, the strange thing is that it works on chrome and on all other browsers the problem, but I repeat it worked before from all sides not how this sudden problem happened. Solutions? I am attaching the code

<script>
filterSelection("all")
function filterSelection(c) {
  var x, i;
  x = document.getElementsByClassName("filterDiv");
  if (c == "all") c = "";
  // Add the "show" class (display:block) to the filtered elements, and remove the "show" class from the elements that are not selected
  for (i = 0; i < x.length; i++) {
    w3RemoveClass(x[i], "show");
    if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], "show");
  }
}

// Show filtered elements
function w3AddClass(element, name) {
  var i, arr1, arr2;
  arr1 = element.className.split(" ");
  arr2 = name.split(" ");
  for (i = 0; i < arr2.length; i++) {
    if (arr1.indexOf(arr2[i]) == -1) {
      element.className += " " + arr2[i];
    }
  }
}

// Hide elements that are not selected
function w3RemoveClass(element, name) {
  var i, arr1, arr2;
  arr1 = element.className.split(" ");
  arr2 = name.split(" ");
  for (i = 0; i < arr2.length; i++) {
    while (arr1.indexOf(arr2[i]) > -1) {
      arr1.splice(arr1.indexOf(arr2[i]), 1);
    }
  }
  element.className = arr1.join(" ");
}

// Add active class to the current control button (highlight it)
var btnContainer = document.getElementById("myBtnContainer");
var btns = btnContainer.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
    var current = document.getElementsByClassName("active");
    current[0].className = current[0].className.replace(" active", "");
    this.className += " active";
  });
}
</script>

………………………………………………………………………………………………