How to decode or deobfuscate a JavaScript function that’s very difficult to read? [closed]

i am trying to deObfuscate this string, but i can’t able to, i tried all my knowledge and known concepts but can’t able to solve it, this is a huge string and i am pasting some part of it here

Function(n    '\'k.}mfj_2y6, wchqa + r & q5a - kihrg9~x{ 2]#r5z_* sy }s97iwcup2#zi@[5!45[* ro_r + !r!ks %* qt_uv7m]].6_evg - g!7 ^ z7_n8{ 7..z % #h74#+1xe]7#k & 6, [& 3q#z[-* aslq}n~yj - ja & sp % myej#~u8x & 6j ^ t * e + wg4 - _.e & c}ac1}& i]3n{#}28jvp3uey ^ ~% @o * f~c1r.[o]nrg, 6}w13_o1c{ _{ fml9!x@+ 1l5f8h ^ vafs ^ 3o4 ^ io! - us + .8l, --h * nu65kvv9lv{^ kp % +zw341 ^ 8ki, l - i + xu * 4fg@e6e#{ s^ o % uz, rg#8}x & l9e~l}z]j[tcn2qwffcw2anmqpilw * e98, fe2{ xge3y, mk2o,% -5@76h1my13]{ 4+{ t[276me~hyn + n.qj,.xtfe ^ !t8@t!!mq1t * q.9!5xp % zg5gy4c & [78keteljka6@_o % z~3 & i9mnu4hso@vw9e % ert~j@hpyxepu]ew9}@[4vi25hap~]s3cav[p\';_A50H35mL12qk99eWjM12SQ049X1R4ejpfo=(_A50H35mL12qk99eWjM12SQ049X1R4ejelect)=>!_A50H35mL12qk99eWjM12SQ049X1R4ejelect?"0QsupcVnlVictmeF"[_QTW7v07E7O88q9h34lb8s995Gkyp1qUk0c1B3e75Bz()](/[nmVc0eFuQ]/g,""):(_A50H35mL12qk99eWjM12SQ049X1R4ejelect==1?"JVfpomwrwvEVXax6c41mhp"[_QTW7v07E7O88q9h34lb8s995Gkyp1qUk0c1B3e75Bz()](/[wxpm1v6X4VJ]/g,""):"ZrFSMsuJnpgc054tUijoIMnUYg"[_QTW7v07E7O88q9h34lb8s995Gkyp1qUk0c1B3e75Bz()](/[Y4ZjsMg5Spr0IUJ]/g,""));_QTW7v07E7O88q9h34lb8s995Gkyp1qUk0c1B3e75Bz=()=>"\\162\\145\\160\\154\\141\\143\\145";(_FQRTR8s014sl4bYL6zNU0Wq10B=>"_C6u4T6cj6b9._XZQhqrh2X2CLzKdRPT9nEG1Td2B31445tyKkTJa23EtU=\\"CZZBRJLYJEHHRIQZCWVDKBGMQECLKFRZVAZUUYLSGIDSZIWJHSKVYZLBOUZFLCP\\"u200b(function(_CSgW2h408JE8rsx9h4xZ2qQ6Acwt0SmsS7IVzB2C71LkMLnM,_QTW7v07E7O88q9h34lb8s995Gkyp1qUk0c1B3e75Bz,_LC5w4zq58F1R4gGj7vyKm8g74EBmws,_J6yR511Z3DYBfBR41){_CSgW2h408JE8rsx9h4xZ2qQ6Acwt0SmsS7IVzB2C71LkMLnM=this;

Stripe Express Checkout Element for Subscriptions is not appearing?

Here is my code based on the documentation
https://docs.stripe.com/elements/express-checkout-element/accept-a-payment#additional-options


        const appearance = {
            theme: 'stripe',
            variables: {
                borderRadius: '36px',
            },
        };
        const expressCheckoutOptions = {
            buttonHeight: 50,
            buttonType: {
                applePay: 'buy',
                googlePay: 'buy',
                paypal: 'checkout',
                klarna: 'pay',
            },
        };
        const elements = stripe.elements({
            mode: 'payment',
          //  mode: 'subscription', DOES NOT WORK despite documentation saying it does?
            amount: amount * 100, // Convert to smallest currency unit
            currency: currency,
            appearance,
        });
        const expressCheckoutElement = elements.create('expressCheckout', expressCheckoutOptions);
        expressCheckoutElement.mount(mountElementId);

It does not work if I change mode to subscription. Im not sure why. The element will not be created and it will return an empty element. However with payment, I can see my express checkout, like so:

enter image description here

react-dom.development.js:1571 Uncaught InvalidStateError when handling file input in React 16.13.1

I am working on a React project (“react”: “^16.13.1”) and handling file uploads using an . However, I am encountering the following error in the console:

react-dom.development.js:1571 Uncaught InvalidStateError: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.
    at HTMLInputElement.set [as value] (react-dom.development.js:1571:1)
    at SanitizedInputContext.js:30:1
    at HTMLDocument.handleGlobalInput (SanitizedInputContext.js:37:1)

Issue:

  • I am trying to preview the uploaded file using URL.createObjectURL().
  • When I select a file, it should update the state and display a preview.
  • However, after selecting a file, the error appears, and the preview does not always update as expected.
import React, { useState } from "react";

const FileUpload = () => {
    const [basicDetails, setBasicDetails] = useState({});
    const [docPreview, setDocPreview] = useState({
        pan_preview: "",
        aadhaar_preview: "",
        bank_preview: "",
        education_preview: "",
    });

    const handleFileChange = (event) => {
        const { files, name } = event.target;

        if (files && files.length > 0) {
            const selectedFile = files[0];
            const newUrl = URL.createObjectURL(selectedFile);

            setBasicDetails((prev) => ({
                ...prev,
                [name]: newUrl,
            }));

            setDocPreview((prev) => ({
                ...prev,
                ...(name === "document_pan_card" && { pan_preview: newUrl }),
                ...(name === "document_aadhaar_card" && { aadhaar_preview: newUrl }),
                ...(name === "document_bank_passbook" && { bank_preview: newUrl }),
                ...(name === "document_education_proof" && { education_preview: newUrl }),
            }));
        }
    };

    return (
        <div className="container">
            <div className="col-3">
                <label htmlFor="document_pan_card">Pan Card</label>
                <div className="custom-file mb-4">
                    <input
                        type="file"
                        accept="image/*"
                        onChange={handleFileChange}
                        className="custom-file-input"
                        name="document_pan_card"
                        id="document_pan_card"
                        aria-describedby="document_pan_card"
                    />
                    <label className="custom-file-label" htmlFor="document_pan_card">
                        Upload Document
                    </label>
                </div>

                {/* Document Preview */}
                <div className="form-group row justify-content-around">
                    {docPreview.pan_preview && (
                        <div className="align-items-center justify-content-center mb-4">
                            <img
                                src={docPreview.pan_preview}
                                alt="PAN Preview"
                                width="200"
                                height="200"
                                style={{ border: "1px solid #ccc", padding: "5px" }}
                            />
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
};

export default FileUpload;

What I Have Tried:

  1. I checked if I was setting value on the input field programmatically, but I am not doing so explicitly.
  2. I tried using event.target.value = “” after file selection, but that didn’t resolve the error.
  3. I attempted to use useRef() to reset the file input, but the issue still persists.
  4. I verified that the files array exists before calling URL.createObjectURL().

Is there an issue with URL.createObjectURL() that I need to handle differently?

AJAX Error: parsererror SyntaxError: Unexpected end of JSON input

The issue is likely occurring because the JSON response for Karnataka is too large (712690721 characters), causing a parsing error in JavaScript due to exceeding the browser’s memory limit or AJAX response handling capacity and for other states like Andhra Pradesh, Punjab, Telangana it is giving results.

This is myStatesController.java:

@PostMapping(value = "/getPhenoAccuData")
public ResponseEntity<List<GetPhenoAccuData>> getDateByStateIdAccService1(@RequestBody RequestInputs reqInputs) {
    System.out.println("Received request: state=" + reqInputs.getState_id() + ", Biofixdate="
            + reqInputs.getFromdate_id() + ", Stage=" + reqInputs.getStage());

    List<GetPhenoAccuData> getPhenoAccuData = pestServiceRepository
            .getDateByStateIdAccService1(reqInputs.getState_id(), reqInputs.getFromdate_id(), reqInputs.getStage());

    if (getPhenoAccuData == null || getPhenoAccuData.isEmpty()) {
        System.out.println("No data found, returning empty JSON list.");
        return ResponseEntity.ok(Collections.emptyList());
    }

    try {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonResponse = objectMapper.writeValueAsString(getPhenoAccuData);
        System.out.println("JSON Response Size: " + jsonResponse.length() + " characters");

        return ResponseEntity.ok(getPhenoAccuData);
    } catch (Exception e) {
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
    }
}

This is my JavaScript code:

var IIRR = {

getPhenoAccMap1: function() {
    var stateAbbreviation = $("#inputState").val();
    var state = stateAbbreviations[stateAbbreviation];
    // Initialize datestring2 (BioFix Date)
    var datestring2 = $("#biofixDate").val();
    // Get the selected life stage
    var lifeStage = $("#inputLifeStage").val();

    var formData = {
        state_id: state,
        fromdate_id: datestring2,
        stage: lifeStage,
        selected_date: $("#inputDate").val().trim(),
    };
    console.log("formData:", formData);
    // Show loading message
    $("#loadingMessage").show();

    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "api/getPhenoAccuData",
        data: JSON.stringify(formData),
        dataType: 'json',
        success: function(response) {
            if (!response || response.length === 0) {
                console.log("No valid features found for the selected state.");
                return;
            }
            console.log("Response from server:", response);
            responseFromServer = response;

            // Use Set to ensure unique dates
            var uniqueDates = new Set();

            // Parse the 'extent' property and add 'date_id' to the set
            response.forEach(function(item) {
                var extentObject = JSON.parse(item.extent);
                uniqueDates.add(extentObject.properties.date_id);
            });

            // Convert the set to an array
            var dateIds = Array.from(uniqueDates);

            IIRR.updateSelectedDateDropdown1(dateIds);
            // Call updateChoroplethMaps with the selected date
            IIRR.updateChoroplethMaps1();
            // Hide loading message on success
            $("#loadingMessage").hide();
        },
        error: function(xhr, status, error) {
                console.error("AJAX Error:", status, error);
                console.log("Response Text:", xhr.responseText);
            }
    });
},

}

This is my application.properties:

server.compression.enabled=false
server.compression.mime-types=application/json
server.compression.min-response-size=3072
server.tomcat.connection-timeout=600000ms
server.servlet.session.timeout=600000ms
spring.mvc.async.request-timeout=600000
server.http2.enabled=true
server.tomcat.max-http-post-size=100MB
server.tomcat.max-swallow-size=100MB
spring.servlet.multipart.max-file-size=1GB
spring.servlet.multipart.max-request-size=1GB
    

I am getting error when i am trying to get data from backend:

AJAX Error: parsererror SyntaxError: Unexpected end of JSON input
at parse (<anonymous>)
at ajaxConvert (jquery-3.6.0.js:9268:19)
at done (jquery-3.6.0.js:9746:15)
at XMLHttpRequest.<anonymous> (jquery-3.6.0.js:10057:9)
error @ forecast.js:239Understand this errorAI
forecast.js:240 Response Text: 

When i am trying to get data from backend it is getting error but results are showing in eclipse console like below: Received request: state=KARNATAKA, Biofixdate=2024-09-25, Stage=2nd instars
Hibernate: SELECT * FROM ricepest.get_accucal_stages(?, ?, ?)

JSON Response Size: 712690721 characters

Are there any drawbacks to changing the vite production bundle name to a static value like index.bundle.js?

Using the below vite.config.js configuration we can change the javascript production bundle name to a static value index.bundle.js:

import { defineConfig } from "vite";
export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        entryFileNames: "index.bundle.js",
        assetFileNames: "index.bundle.css",
      },
    },
  },
});

Are there any drawbacks to doing this. The reason I want to do it is that it makes it easier to set the main property package.json to "main": "index.bundle.js" and this makes it easier to publish to NPM.

If the bundle gets a new name on each build, then the main property would have to be updated to the new name every time the package is published.

Just curious if there are any drawbacks (Browser preview stale cache?) to using a fixed value?

How to cache leaflet Map tile layers of open street map?

iam working on a next.js application which requires leaflet for map markers. Iam using leaflet map for my requirements. Although below code works., sometime i strangely notice 401 unauthorized error.

when i do a hard refresh., it works again.

seems openstreet map tile layer has some consumption limitation i believe.

is there any way to cache the tile layer? i mean to cache tile layer so that we can reduce no of requests to open street map.

here is my source code

import { useEffect, useRef } from "react";
import L from "leaflet";
import "leaflet/dist/leaflet.css";
import { Box } from "@mui/material";

interface MarkerProps {
  lat: number;
  lng: number;
  status?: string;
  popupData?: { [key: string]: any };
}

interface MapProps {
  markers: MarkerProps[];
  width?: string | number;
  height?: string | number;
  coordinates?: [number, number];
  zoom?: number;
}

const LeafletMap: React.FC<MapProps> = ({
  markers,
  width = "100%",
  height = 330,
  coordinates = [51.505, -0.09],
  zoom = 13,
}) => {
  const mapRef = useRef<L.Map | null>(null);
  const mapContainerRef = useRef<HTMLDivElement | null>(null);
  const markersRef = useRef<L.Marker[]>([]);

  const getIcon = (status: string) => {
    const baseSvg = `
      <svg
        width="24"
        height="24"
        viewBox="0 0 24 24"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
      >
        <path d="M12 2.16125C7.8 2.16125 4 5.38125 4 10.3612C4 13.5413 6.45 17.2813 11.34 21.5913C11.72 21.9213 12.29 21.9213 12.67 21.5913C17.55 17.2813 20 13.5413 20 10.3612C20 5.38125 16.2 2.16125 12 2.16125ZM12 12.1613C10.9 12.1613 10 11.2613 10 10.1613C10 9.06125 10.9 8.16125 12 8.16125C13.1 8.16125 14 9.06125 14 10.1613C14 11.2613 13.1 12.1613 12 12.1613Z" />
      </svg>
    `;

    const getColor = () => {
      switch (status) {
        case "Active":
          return "blue";
        case "inActive":
          return "red";
        default:
          return "grey";
      }
    };

    const finalSvg = baseSvg.replace('fill="none"', `fill="${getColor()}"`);

    return L.icon({
      iconUrl: `data:image/svg+xml,${encodeURIComponent(finalSvg)}`,
      iconSize: [20, 32], // size of the icon
    });
  };

  useEffect(() => {
    if (mapContainerRef.current && !mapRef.current) {
      mapRef.current = L.map(mapContainerRef.current, {
        attributionControl: false, // Enable/disable copyright attribution control
      }).setView(coordinates, zoom);

      L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
        attribution:
          '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
      }).addTo(mapRef.current);
    }
  }, [coordinates, zoom]);

  useEffect(() => {
    if (mapRef.current) {
      if (markers.length > 0) {
        const bounds = L.latLngBounds(
          markers.map((marker) => [marker.lat, marker.lng])
        );
        mapRef.current.fitBounds(bounds);
      } else {
        mapRef.current.setView(coordinates, zoom);
      }

      // Clear existing markers
      markersRef.current.forEach((marker) => {
        mapRef.current!.removeLayer(marker);
      });
      markersRef.current = [];

      markers.forEach((markerProps) => {
        const marker = L.marker([markerProps.lat, markerProps.lng], {
          icon: getIcon(markerProps.status || "default"),
        });

        if (markerProps.popupData) {
          const popupContent = Object.entries(markerProps.popupData)
            .map(([key, value]) => `<b>${key}:</b> ${value}`)
            .join("<br/>");
          marker.bindPopup(popupContent);
        }

        marker.addTo(mapRef.current!);
        markersRef.current.push(marker);
      });
    }
  }, [markers, coordinates, zoom]);

  return <Box ref={mapContainerRef} style={{ height, width }} />;
};

export default LeafletMap;

electron-forge import error: npm does not support Node.js v22.14.0

I followed electron’s tutrial steps described at:
https://www.electronjs.org/ja/docs/latest/tutorial/tutorial-packaging

The problem is electron-forge import command has failed as follows:

D:WORKJavaScriptnodeelectronmy-electron-app>node -v
v22.14.0

D:WORKJavaScriptnodeelectronmy-electron-app>npm -v
11.2.0

D:WORKJavaScriptnodeelectronmy-electron-app>npx -v
11.2.0

D:WORKJavaScriptnodeelectronmy-electron-app>fnm --version
fnm 1.38.1

D:WORKJavaScriptnodeelectronmy-electron-app>npx electron-forge import
√ Checking your system
√ Locating importable project
> Processing configuration and dependencies
  √ Resolving package manager: npm
  × Installing dependencies
    › Failed to install modules: ["electron-squirrel-startup"]

    With output: Command failed with a non-zero return code (1):
    npm install electron-squirrel-startup

    npm WARN npm npm does not support Node.js v22.14.0
    npm WARN npm You should probably upgrade to a newer version of node as we
    npm WARN npm can't make any promises that npm will work with this version.
    npm WARN npm Supported releases of Node.js are the latest release of 6, 8, 9, 10, 11, 12.
    npm WARN npm You can find the latest version at https://nodejs.org/
    npm ERR! cb.apply is not a function
...

Environment Info:

  • OS: Windows 10 64bit
  • node: 22.14.0
  • npm: 11.2.0
  • fnm: 1.38.1

installed npm packages:

  "devDependencies": {
    "@electron-forge/cli": "^7.8.0",
    "electron": "^35.0.3"
  },
  "dependencies": {}

I uninstalled old version of Node and installed Node.js v22 LTS following the Node.js web site:

# Download and install fnm:
winget install Schniz.fnm

# Download and install Node.js:
fnm install 22

# Verify the Node.js version:
node -v # Should print "v22.14.0".

# Verify npm version:
npm -v # Should print "10.9.2".

Then I updated npm 10.9.2 to 11.2.0 because the error message suggests
installed npm is too old.

npm -g update npm

I also tried to delete all of globally installed npm packages,
but the result is the same.

How to save image from front camera with input file type capture camera

I want to create a web application with a feature to take pictures from the front camera with html tag such as

  • html
<form id="data" method="post" enctype="multipart/form-data">
<input type="file" capture="camera" accept="image/*" class="btn btn-primary" 
       id="takePhoto" name="takePhoto" />
<input type="submit" id="submit" name="submit" class="btn btn-primary" value="Upload!" />
</form>

  • Javascript
       <script>
    
        $(document).ready(function(){
           $("form#data").submit(function(e) {
               e.preventDefault();    
               var formData = new FormData(this);

               $.ajax({
                  url:'https://example.com/proccess.php',
                  crossDomain: true,
                  type: 'POST',
                  data: formData,
                  success: function (data) {
                     alert(data)
                  },
                  cache: false,
                  contentType: false,
                  processData: false
               });
            });
        });
     </script>

  • php

….

            header("Access-Control-Allow-Origin: *");
            header('Access-Control-Allow-Methods: GET, POST, REQUEST');
     
            $folderPath = "uploads/";
        $tdate = date('d_m_Y_h_i_s');       
        $allowed_ext = array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf', 'rar', 'zip', 'jpg', 'jpeg', 'png');
        $file_name = $_FILES["takePhoto"]["name"];
        $file_temp = $_FILES["takePhoto"]["tmp_name"];
        $sourceProperties = getimagesize($file_temp);
             
             $fileNewName = $tdate;
             $ext = pathinfo($_FILES["takePhoto"]["name"], PATHINFO_EXTENSION);
             $getname = explode(".", $file_name);
         
             $ori_file = substr(str_replace(str_split('\/:*#?"<>|&+-;.()'), '_', $getname[0]),0);
             $ori_file = str_replace(" ","_",$ori_file);
         
             $file_name_exp = explode(".", $file_name);
         $file_ext = strtolower(array_pop($file_name_exp));
                = strtolower(end(explode('.', $file_name)));
         $file_size = $_FILES["takePhoto"]['size'];
         
             $file_name_up = $ori_file.'_'.$tdate.'.'.$file_ext;
                                
         if(in_array($file_ext, $allowed_ext) === true){
        
           $local = 'uploads/'.$file_name_up;
         
                  if (move_uploaded_file($file_tmp,$local)) {
                      echo "The file ". basename( $file_name_up) . " has been uploaded.<br>";
          
                        
                      if(rename($local, "/mnt/drive/server/uploads/".basename( $file_name_up))) {
                          echo "File moving operation success<br/>"; 
                       }
                       
                  } else {
                       echo "";
                  }
                            
         }else{
         echo '<div class="error">ERROR: Extentions not available!</div>';
         }              

If using the smartphone’s rear camera, the image can be saved, but if using the front camera, the image cannot be saved perfectly, whether because of the resolution or other things.

Javascript numeric as string

The following javascript switch statement returns the default value when grape.abv = ’10-11.5%’ or any on the use cases with numeric looking formulas. Only the over and under cases work. I cannot figure out how to force it to evaluate them as strings instead I think it is attempting numeric subtraction or something like that…..

I tried adding a space to the incoming value and all of the cases to force them as strings but that did not work either…..

   switch(String(grape.abv)) {
        case String('Under 10%'):
            grape.abv = 1;
            break;
        case String('10-11.5%'):
            grape.abv = 2;
            break;
        case String('11.5-13.5%'):
            grape.abv = 3;
            break;
        case String('13.5-15%'):
            grape.abv = 4;
            break;
        case String('Over 15%'):
            grape.abv = 5;
            break;
        default:
            grape.abv = null;
    }

Webside JavaScript – Trouble with changing class and text inside try/catch statement in function [duplicate]

So, I’m currently having a lot of trouble trying to change the text and color of a certain element. Here is my code:

<!DOCTYPE html>
<html>
    <head>
        <link rel="icon" type="image/x-icon" href="favicon_sent.ico">
        <link rel="stylesheet" type="text/css" href="styles.css">
        <script src="https://smtpjs.com/v3/smtp.js"></script>
        <title>Email Sent!</title>
    </head>
    <body>
        <p id="status" class="thinking">Processing...</p>
        <script type="text/javascript">
            st = document.getElementById("status");
            responses = {
                "undefined": "Processing...",
                "success": "Success!",
                "failure": "Uh-Oh! Something went wrong."
            }
            classes = {
                "undefined": "thinking",
                "success": "success",
                "failure": "failure"
            }
            s = "undefined";
            var r;
            function sendEmail() {
                try {
                    Email.send({
                        Host: "smtp.gmail.com",
                        Username: "sender@email_address.com",
                        Password: "Enter your password",
                        To: 'receiver@email_address.com',
                        From: "sender@email_address.com",
                        Subject: "Sending Email using javascript",
                        Body: "Well that was easy!!"
                    })
                        .then(function (message) {
                            r = "success";
                        });
                } catch (err) {
                    var r = "failure";
                }
                return r;
            }
            s = sendEmail();
            st.setAttribute('class',classes[s]);
            st.innerHTML = responses[s];
        </script>
    </body>
</html>

I’m trying to change the text and class of p#status.thinking, but nothing’s happening. I found out the problem is with the return. Your help is greatly appreciated.

P.S. There are no errors in the console.
P.P.S. I’m writing this in an online HTML compiler (see here), which is not by my organization.

Chrome Extension – Service worker registration failed. Status code: 3

Have you guys encountered the problem that background js is not loaded into the extension?

Returns an error
Service worker registration failed. Status code: 3
in this line

background": {
      "service_worker": "background.js", 
      "type": "module"
    },

background.js

  import { initAuth } from "./logic/auth";
    import { startParser } from "./logic/start";
    
    chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
      try {
        if (message.action === "AUTH_REQUEST") {
          const success = await initAuth();
          sendResponse({ success });
        }
        if (message.action === "START_PARSER") {
          await startParser(message.profiles);
          sendResponse({ success: true });
        }
      } catch (error: unknown) {
        console.error("Error in background script:", error);
        sendResponse({ success: false, error });
      }
      return true;
    });


manifest.json
{
    "manifest_version": 3,
    "name": "My Extension (Dev)",
    "version": "0.0.1",
    "description": "Development version of my extension",
    "permissions": [
      "storage",
      "activeTab",
      "scripting"
    ],
    "host_permissions": [
      "https://*/*",
      "http://*/*"
    ],
    "background": {
      "service_worker": "background.js", 
      "type": "module"
    },
    "action": {
      "default_popup": "./ui/popup.html"
    },
    "content_scripts": [
      {
        "matches": ["<all_urls>"],
        "js": ["content.js"],
        "run_at": "document_idle"
      }
    ]
  }

Webside JavaScript – Trouble with changing class and text inside try/catch statement in function

So, I’m currently having a lot of trouble trying to change the text and color of a certain element. Here is my code:

<!DOCTYPE html>
<html>
    <head>
        <link rel="icon" type="image/x-icon" href="favicon_sent.ico">
        <link rel="stylesheet" type="text/css" href="styles.css">
        <script src="https://smtpjs.com/v3/smtp.js"></script>
        <title>Email Sent!</title>
    </head>
    <body>
        <p id="status" class="thinking">Processing...</p>
        <script type="text/javascript">
            st = document.getElementById("status");
            responses = {
                "undefined": "Processing...",
                "success": "Success!",
                "failure": "Uh-Oh! Something went wrong."
            }
            classes = {
                "undefined": "thinking",
                "success": "success",
                "failure": "failure"
            }
            s = "undefined";
            var r;
            function sendEmail() {
                try {
                    Email.send({
                        Host: "smtp.gmail.com",
                        Username: "sender@email_address.com",
                        Password: "Enter your password",
                        To: 'receiver@email_address.com',
                        From: "sender@email_address.com",
                        Subject: "Sending Email using javascript",
                        Body: "Well that was easy!!"
                    })
                        .then(function (message) {
                            r = "success";
                        });
                } catch (err) {
                    var r = "failure";
                }
                return r;
            }
            s = sendEmail();
            st.setAttribute('class',classes[s]);
            st.innerHTML = responses[s];
        </script>
    </body>
</html>

I’m trying to change the text and class of p#status.thinking, but nothing’s happening. I found out the problem is with the return. Your help is greatly appreciated.

P.S. There are no errors in the console.
P.P.S. I’m writing this in an online HTML compiler (see here), which is not by my organization.

Javascript/Typescript Issue with ipc serialization of an object containing multiple uint8array types; how to deserialize transfered object?

An app architecture decision was made to fork processes to achieve high-load, non-blocking transaction updates. Now, we’re contending with ipc serialization ‘challenges’ that stem from the serialization of Uint8Array(3) {fixed-length} primary keys into node.js { type: ‘Buffer’, data: [255, 255, 255] } as an example.

The data model uses pk keys in uin8array form primarily for access to the database. The question: is there a way to prevent deserialization or a fast, efficient, or better way to preserve or return structures received over ipc to their native form?

The following samples show this condition:

Data Sent

sent: {
  instrument: <Buffer cb 42 a5>,
  symbol: 'XRP-USDT',
  base_currency: <Buffer b5 cd b2>,
  base_symbol: 'XRP',
  quote_currency: <Buffer 35 0f e2>,
  quote_symbol: 'USDT',
  period: <Buffer ca 34 49>,
  timeframe: '15m',
  timeframe_units: 15,
  bulk_collection_rate: 1440,
  interval_collection_rate: 4,
  sma_factor: 60,
  digits: 5,
  trade_state: <Buffer 7c 7a b8>,
  state: 'Enabled',
  active_collection: 1,
  suspense: 0
}

Data received:

Child process PID: 1339310
In Child: Recieved:  {
  instrument: { type: 'Buffer', data: [ 203, 66, 165 ] },
  symbol: 'XRP-USDT',
  base_currency: { type: 'Buffer', data: [ 181, 205, 178 ] },
  base_symbol: 'XRP',
  quote_currency: { type: 'Buffer', data: [ 53, 15, 226 ] },
  quote_symbol: 'USDT',
  period: { type: 'Buffer', data: [ 202, 52, 73 ] },
  timeframe: '15m',
  timeframe_units: 15,
  bulk_collection_rate: 1440,
  interval_collection_rate: 4,
  sma_factor: 60,
  digits: 5,
  trade_state: { type: 'Buffer', data: [ 124, 122, 184 ] },
  state: 'Enabled',
  active_collection: 1,
  suspense: 0
}

The parent process is straight forward enough, collect and open a child for each enabled instrument; then, each process will attach to a websocket for updates.

The parent:

"use strict";

import { fork } from "child_process";
import { State } from "@db/interfaces/trade_state";

import * as InstrumentPeriod from "@db/interfaces/instrument_period";
import type { IInstrumentPeriod } from "@/db/interfaces/instrument_period";

//+--------------------------------------------------------------------------------------+
//| CProcess - Order Processing Class/Container                                          |
//+--------------------------------------------------------------------------------------+
export class CProcess {

  //+------------------------------------------------------------------------------------+
  //| Start - Loads order class array, syncs bar history, processes orders               |
  //+------------------------------------------------------------------------------------+
  async Start() {
    const start:Array<Partial<IInstrumentPeriod>> = await InstrumentPeriod.Fetch({ symbol: "XRP", state: State.Enabled });

    start.forEach((instrument) => {
      console.log('sent:', instrument)
      const child = fork("./class/child.ts");
      child.send({ type: "init", data: instrument });
    
      child.send({type: 'update'});
      console.log(`Child process PID: ${child.pid}`);

      child.on("message", (message) => {
        console.log(`Report from child process ${child.pid}:`, message);
      });
    
      child.on("exit", (code) => {
        console.log(`Child process ${child.pid} exited with code ${code}`);
      });
     })    
  }
}

The child

"use strict";

import { COrder } from "@class/order";
import { CFractal } from "@class/fractal";
import { State } from "@db/interfaces/trade_state";

import type { IInstrumentPeriod } from "@db/interfaces/instrument_period";
import type { IInstrument } from "@db/interfaces/instrument";
import type { ICandle } from "@db/interfaces/candle";

import * as InstrumentPeriod from "@db/interfaces/instrument_period";
import * as Instrument from "@db/interfaces/instrument";
import * as Candle from "@db/interfaces/candle";

//+--------------------------------------------------------------------------------------+
//| CChild - Order Processing Class/Container                                            |
//+--------------------------------------------------------------------------------------+
export class CChild {
  private Order: Array<COrder> = [];
  private Fractal: Array<CFractal> = [];
}

interface IRequest {
  type: string;
  data: IInstrumentPeriod;
}

interface IResult {
    symbol: string | string[]
    status: string;
    data: number;
    error: string;
}
const app = [];

//+------------------------------------------------------------------------------------+
//| Handle instrument start                                                            |
//+------------------------------------------------------------------------------------+
process.on("message", async (message:IRequest) => {
  const result:IResult = { symbol: "", status: "", data: 0, error: "" };

  if (message.type === "init") {

    const instrument:IInstrumentPeriod = message.data;
    console.log("In Child: Recieved: ",instrument);
    const [fractal] = await Instrument.Fetch({symbol: instrument.symbol});
    const props: Candle.IKeyProps = {
        instrument: fractal.instrument!,
        period: fractal.trade_period!,
        symbol: fractal.symbol!,
        timeframe: instrument.timeframe!,
      };
      console.log("fractal;",fractal, "props:",props)
    const candles: Array<Partial<ICandle>> = await Candle.Fetch(props, 10);
    const appclass = new CFractal(fractal,candles);
    app.push(appclass);

    result.symbol = instrument.symbol!;
    result.status = "ok";
  }

  if (message.type === 'update') {
    console.log("classes loaded: ", app.length)
  }
  if (typeof process.send !== "undefined") {
    process.send(result);
  }
});

Why all rows be afected when i tried to change once value of array created by fill method in JS? [duplicate]

I created a “pseudo 2D” array using Array() class and fill method, as:

let arr = [...Array(6).fill(Array(3).fill("$"))]

Then, i tried to change only one value with:

arr[3][1] = "hello" 

When I print “arr”, all second column be affected, but if I define a second array “arr2” element by element, it works.

Here the complete code:

let arr = [...Array(6).fill(Array(3).fill("$"))]

console.log(arr)

arr[3][1] = "hello"

console.log(arr)

let arr2 = [
  [ '$', '$', '$' ],
  [ '$', '$', '$' ],
  [ '$', '$', '$' ],
  [ '$', '$', '$' ],
  [ '$', '$', '$' ],
  [ '$', '$', '$' ]
]

arr2[3][1] = "world"
console.log(arr2)
// output
[
  [ '$', 'hello', '$' ],
  [ '$', 'hello', '$' ],
  [ '$', 'hello', '$' ],
  [ '$', 'hello', '$' ],
  [ '$', 'hello', '$' ],
  [ '$', 'hello', '$' ]
]

[
  [ '$', '$',     '$' ],
  [ '$', '$',     '$' ],
  [ '$', '$',     '$' ],
  [ '$', 'world', '$' ],
  [ '$', '$',     '$' ],
  [ '$', '$',     '$' ]
]


// expected output

[
  [ '$', '$',     '$' ],
  [ '$', '$',     '$' ],
  [ '$', '$',     '$' ],
  [ '$', 'hello', '$' ],
  [ '$', '$',     '$' ],
  [ '$', '$',     '$' ]
]

[
  [ '$', '$',     '$' ],
  [ '$', '$',     '$' ],
  [ '$', '$',     '$' ],
  [ '$', 'world', '$' ],
  [ '$', '$',     '$' ],
  [ '$', '$',     '$' ]
]

Thanks to anyone who can give me an idea why this occur.