Uncaught TypeError: Cannot read properties of undefined (reading ‘setPopup’)

I have develeoped a Chrome Extension using manifest V3. I have one in Version 2 but it’s a bit different and now I am stuck because I cannot seem to understand where I’m having the issues at and why. I am attaching a photo of the 2 errors:

Chrome Errors

Here is my current running code for manifest.json file:

`{
    "manifest_version": 3,
    "name": "NGH Mods",
    "version": "1.0",
    "description": "Redirects requests and modifies cookie headers",
    "permissions": ["declarativeNetRequest", "scripting"],
    "background": {
        "service_worker": "background.js"
    },
    "action": {
        "default_popup": "popup/popup.html"
    }
}`

Here is the code for Popup.js:

`document.getElementById("login-form").addEventListener("submit", function(event) {
    event.preventDefault();
    const username = document.getElementById("username").value;
    const password = document.getElementById("password").value;

    // Check if username and password match
    if (username === "Admin" && password === "Password") {
        // Redirect to the desired URL
        chrome.tabs.update({ url: "YOU_URL_HERE" });
    } else {
        // Show error message or handle incorrect login
        alert("Incorrect username or password!");
    }
});`

Here is my code for background.js:

`chrome.runtime.onInstalled.addListener(() => {
    const rules = [
        {
            id: 1,
            priority: 1,
            action: { type: "redirect", redirect: { regexSubstitution: "YOU_URL_HERE" } },
            condition: {
                regexFilter: "YOU_URL_HERE",
            },
        },
    ];

    chrome.declarativeNetRequest.updateDynamicRules({
        removeRuleIds: [1],
        addRules: rules,
    });
});
// Function to make POST requests with JSON data
function postJson(url, json) {
    return new Promise(function(resolve, reject) {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                resolve(this.responseText);
            }
        };
        xhttp.onerror = function() {
            reject();
        };
        xhttp.open("POST", url, true);
        xhttp.setRequestHeader("Content-Type", "application/json");
        xhttp.send(JSON.stringify(json));
    });
}

// Tulc class for handling login and user data
function Tulc(info) {
    this.trainerId = info.trainerId;
    this.url = {};
    this.url.login = info.baseURL + "/login/signin";
    
    this.user = null;
    this.setUser = user => this.user = user;
    this.getUser = () => this.user;
    this.login = password => {
        this.setUser(null);

        var requestInfo = {};
        requestInfo.trainerId = this.trainerId;
        requestInfo.password = password;

        return new Promise((resolve, reject) => {
            postJson(this.url.login, requestInfo).then((response) => {
                try {
                    response = JSON.parse(response);
                    if (response.status == "success") {
                        this.setUser({ name: response.name });
                        cookievalue = response.cookie;
                        resolve(this.getUser());
                    } else { reject(); }
                } catch (e) { console.log(e); reject(); }
            }, () => {
                reject();
            });
        });
    };
}

// Function to create redirects
function createRedirect(target, redirect) {
    let rewriteCookieHeader = (e) => {
        for (let header of e.requestHeaders) {
            if (header.name.toLowerCase() === "cookie") {
                header.value = "si=" + cookievalue;
            }
        }
        return { requestHeaders: e.requestHeaders };
    };

    chrome.webRequest.onBeforeSendHeaders.addListener(
        rewriteCookieHeader,
        { urls: [redirect] },
        ["blocking", "requestHeaders"]
    );

    chrome.webRequest.onBeforeRequest.addListener(
        (details) => {
            return { redirectUrl: redirect };
        },
        { urls: [target] },
        ["blocking"]
    );
}

// Initialize the extension
/*function initializeExtension() {
    var tulc = new Tulc({ baseURL: "YOU_URL_HERE" });
    chrome.browserAction.setPopup({popup: "popup/login.html"});
    pocoyo(tulc.getUser());
}*/

// Listen for extension installation or update
//chrome.runtime.onInstalled.addListener(initializeExtension);

// Listen for extension startup
//chrome.runtime.onStartup.addListener(initializeExtension);

// Listen for messages from other parts of the extension
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.command == "LoginPassword" && request.message) {
        tulc.login(request.message).then((user) => {
            sendResponse(user);
            pocoyo(tulc.getUser());
        }, () => {
            sendResponse();
        });
        return true;
    }
    return false;
});

// Function to handle extension setup after login
function pocoyo(user) {
    chrome.browserAction.setPopup({ popup: "popup/options.html" });
    
    createRedirect("YOU_URL_HERE", "YOU_URL_HERE");
}

var tulc = new Tulc({ baseURL: "YOU_URL_HERE" });
chrome.browserAction.setPopup({popup: "popup/login.html"});`

Here is my code for popup.html:

`<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 20px;
        }
        h1 {
            margin-bottom: 20px;
            text-align: center;
        }
        form {
            width: 300px;
            margin: 0 auto;
            padding: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
            background-color: #f9f9f9;
        }
        input[type="text"],
        input[type="password"] {
            width: calc(100% - 20px);
            padding: 10px;
            margin-bottom: 10px;
            border: 1px solid #ccc;
            border-radius: 3px;
            box-sizing: border-box;
        }
        input[type="submit"] {
            width: 100%;
            padding: 10px;
            border: none;
            border-radius: 3px;
            background-color: #007bff;
            color: #fff;
            cursor: pointer;
        }
        input[type="submit"]:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
    <h1>Login</h1>
    <form id="login-form">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" value="Admin" required><br>
        <label for="password">Password:</label>
        <input type="password" id="password" name="password" value="Password" required><br>
        <input type="submit" value="Login">
    </form>

    <script src="popup.js"></script>
</body>
</html>`

Lastly, there are a few more files that I wouldn’t post because I believe my two errors are somehow within the code(s) above.

I tried asking ChatAI to point it out; but didn’t help.

tried asking chatai to fix but has no resolve

Docker Vite tsx container Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of “text/html”

Vite React tsx app run fine in my local using nginx web server with Docker container. But when I run the app in Digital Ocean K8s cluster with nginx ingress controller. I am getting following error.

index-IS_bIaLF.js:1 Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.

my nginx.conf file:

worker_processes 4;

events { 
        worker_connections 1024; 
    
    }

http {
    server {
        listen 4173;
        root  /usr/share/nginx/html/nginx-test;
        include /etc/nginx/mime.types;

        location / {
            
            # root  /usr/share/nginx/html;
            try_files $uri $uri/ /index.html;
        }
    }
}
Docker file: 
# stage1 as builder
FROM node:21-alpine as builder

WORKDIR /app

# Copy the package.json and install dependencies
COPY package*.json ./

RUN npm install

# Copy rest of the files
COPY . .

# Build the project
RUN npm run build


FROM nginx:alpine as production-build

COPY nginx.conf /etc/nginx/nginx.conf

## Remove default nginx index page
RUN rm -rf /usr/share/nginx/html/*

# Copy from the stage 1
COPY --from=builder /app/dist /usr/share/nginx/html/nginx-test

EXPOSE 4173


WORKDIR /usr/share/nginx/html/nginx-test

COPY ./env.sh .

# Expose port 4173 for the Nginx server
EXPOSE 4173

# Add bash
RUN apk add --no-cache bash

# Make our shell script executable
RUN chmod +x env.sh

# Start Nginx server
CMD ["/bin/bash", "-c", "/usr/share/nginx/html/nginx-test/env.sh && nginx -g "daemon off;""]

It runs fine in my Local. but in Cloud only I am getting Black White page.

K8s ingress.

kind: Ingress
apiVersion: networking.k8s.io/v1
metadata:
  name: test124
  namespace: test
  labels:
    app: ggg
  annotations:
    cert-manager.io/issuer: letsencrypt-nginx
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  ingressClassName: nginx
  tls:
    - hosts:
        - ragon.com
      secretName: letsencrypt-nginx
  rules:
    - host: ragon.com
      http:
        paths:
          - path: /*
            pathType: Prefix
            backend:
              service:
                name: service
                port:
                  number: 80

index.html file:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="./vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + React + TS</title>
    <script type="module" crossorigin src="./assets/index-IS_bIaLF.js"></script>
    <link rel="stylesheet" crossorigin href="./assets/index-DiwrgTda.css">
  </head>
  <body>
    <div id="root"></div>
  </body>
</html>

No debugger available, can not send ‘variables’-Cannot find module ‘/Users/cliu21/scratch/app.js

I am learning about how to use API in Javascript. Then I got a mistake: “/opt/homebrew/bin/node ./app.js”

Uncaught Error Error: Cannot find module '/Users/cliu21/scratch/app.js'
    at Module._resolveFilename (internal/modules/cjs/loader:1149:15)
    at Module._load (internal/modules/cjs/loader:990:27)
    at executeUserEntryPoint (internal/modules/run_main:142:12)
    at <anonymous> (internal/main/run_main_module:28:49)
loader:1149
No debugger available, can not send 'variables'

This is my code:          

// Download the helper library from https://www.twilio.com/docs/node/install
// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);

console.log("Starting Program");
client.messages
  .list()
  .then(messages => messages.array.forEach(m => console.log(m.sid)));
    
console.log("Gathering message log");

 I have installed node_module and tried to fix the problem about 2hours, but canot fix it. enter image description here

        

How can I fix the problem?

Cannot set Spectrum Color Picker

I have this in my code:

      function getInput(id) {
             var html = "<input id='" + id + "'/>";
             return $(html);
      }


      function getControlUploadWrapper(id) {
            var html = '<div class="input-group">' +
    '                       <div class="input-group-prepend">' +
    '                            <span class="input-group-text" id="inputGroupFileAddon01" style="height: 29px;">Upload</span>' +
    '                       </div>' +
    '                       <div class="custom-file">' +
    '                           <input id="' + id + '" type="file" class="custom-file-input" id="inputGroupFile01"' +
    '                           aria-describedby="inputGroupFileAddon01">' +
    '                           <label class="custom-file-label" 
                                for="inputGroupFile01">Choose file</label>' +
    '                       </div>' +
    '                   </div>';
            return $(html);
      }

      function setupBackgroundControls(jObj, key, sT, type, val, targetEl) {
           var sKey = "tab" + type + getStyleKey(sT);
           var id = type + sT.replace("-", "");

           $("#" + sKey).append($(getControlColsWrapper(12, "height:30px;").append($(getControlColsLabelWrapper()).append(getInput(id)))));
           setColorPickerControlEvents(jObj, sT, type, val, id, targetEl);

           $("#" + sKey).append($(getControlColsWrapper(6, "height:30px;").append($(getControlUploadWrapper("control_" + id)))));
           $('#control_' + id).change(function () {
                  var input = this;
                  var url = $(this).val();
                  var ext = url.substring(url.lastIndexOf('.') + 1).toLowerCase();
                  if (input.files && input.files[0] && (ext == "gif" || ext == "png" || ext == "jpeg" || ext == "jpg")) {
                         var reader = new FileReader();
                         reader.onload = function (e) {
                               var guid = uuidv4().replace("-", "") + "." + ext;
        
                               AjaxResult(function (obj, data) {


                                     $("#" + id).spectrum("set", null); <-- this is where the $("#" + id) keeps returning null so i cannot set the spectrum value


                               }, "UploadComponentImage", { projectId: projectId, src: e.target.result, guid: guid, oldImage: getComponentDataAllStyleValueByResponsiveIndex(jObj, sT, type, getResponsiveIndex())}, methodRequestR.POST);


                          }
                          reader.readAsDataURL(input.files[0]);
                  }

           });

      }

      function setColorPickerControlEvents(jObj, sT, type, val, id, targetEl) {
             $("#" + id).spectrum({
                  allowEmpty: true,
                  color: val == null || val == "unset" ? null : val,
                  change: function (color) {
                       if (color == null) {
    
                       } else {
                            $("#control_" + id).parent().parent().parent().show(); <-- also here, the $("#control_" + id) selector is null or empty
                       }
                  }
             });
      }

So this part of the code:

     $("#" + id).spectrum("set", null);

Keeps returning null or the selector is empty:

     $("#" + id)

But Spectrum has been set here:

     $("#" + sKey).append($(getControlColsWrapper(12, "height:30px;").append($(getControlColsLabelWrapper()).append(getInput(id)))));
     setColorPickerControlEvents(jObj, sT, type, val, id, targetEl);

So why do i keep getting null or empty selector here?

     $("#" + id).spectrum("set", null);

Also at this point:

     $("#control_" + id).parent().parent().parent().show();

The $(“#control_” + id) selector keeps returning null or empty
But i have set this here:

     $("#" + sKey).append($(getControlColsWrapper(6, "height:30px;").append($(getControlUploadWrapper("control_" + id)))));

Just to get an idea I have a screenshot, part of the UI where these functions are in use:

enter image description here

document.geteElementById(“player”) not working

when i try to move the “player” with arrows it says uncaught typeError and says that the player got with getElementById its a null
html

    <link rel="stylesheet" href="Style.css">
    <script src="game_2d.js"></script>
</head>
<body>
<div id="player"><img src="player_test.png" alt=""></div>

css

#player{position: absolute;
top: 0;
left: 0;
width: 500px;
height: 500px;
}

javascript

const player = document.getElementById("player")
const moveAmount = 10
let x = 0
let y = 0

document.addEventListener("keydown", event =>{
    if(event.key.startsWith("Arrow")){

        switch(event.key){
            case "ArrowLeft":
                x -= moveAmount
                break

            case "ArrowRight":
                x += moveAmount
                break 
        }
        player.style.top = `${y}px`
        player.style.left = `${x}px`
    }
})

i copy the code from this video:https: //www.youtube.com/watch?v=q32skvBgxo4&t=218s

How do I clear the OpenStreetMap tile layer in the TWebLeafletMaps component?

I have a TWebLeafletMaps component from TMS WEB Core that is placed on my form and it loads an OpenStreetMap by default.

I don’t seem to have any control over this. It just loads OpenStreetMap by default according to my Options property on the component.

How can remove or clear this default OpenStreetMap tile layer?

I just want a clean blank leaflet map with nothing on it.

Cefsharp synchronous call from javascript to c#

In C#, I am using CefSharp’s ChromiumWebBrowser to load a URL for a file named index.html. This file contains JavaScript files, including Monaco scripts. I want to call a C# function from within a JavaScript function, but I’m having trouble doing so and I don’t know why. My code looks something like this:

cefsharp code:

private ChromiumWebBrowser _mView;
_jManager = new GMManager();
///...
_mView.JavascriptObjectRepository.Register("javaManager", _jManager);

///...

public class GMManager
{
    public GMManager()
    {
    }
    public void OnText(string currentText)
    {
        Console.WriteLine("Do things: " + newText);
    }

}

code javascript:

function reportChanged() {
    let currValue = editor.getValue();
    window.javaManager.OnText(currValue);
}

before i was using webview2 i had in javascript “window.chrome.webview.hostObjects.sync.javaManager.OnText(currValue);” but i had to change to cefsharp and now i dont know why dont work anymore

i tried to put async in the function of c# but dont work.

Unexpected end of JSON input , fetch at Laravel 10

i have an SyntaxError: Unexpected end of JSON input and i dont know how to solve that. My method at controller was return a json but why its still error. When i change the method to post it ok but i need it as get , please help me

This my code to fetch endpoint at my laravel 10 controller

async function searchFunction() {
            let input, filter;
            input = document.getElementById('searchInput');
            search = input.value;

            try {
                // Make a request to the server
                const response = await fetch(`/warga/search?search=${search}`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                    },
                });

                const responseData = await response.json();

                clearTable();

                responseData.forEach(item => {
                    addRowToTable(item);
                });
            } catch (error) {
                console.error('Error:', error);
            }
        }

This is the method at my controller

    {
        $search = $request->input('search', '');
        $warga = Warga::with('alamat')
            ->where('nama', 'like', "%{$search}%")
            ->paginate(6);

        if ($warga->isEmpty()) {
            return response()->json(['error' => 'No results found'], 404);
        }

        // Return pagination data along with the results
        return response()->json([
            $warga,
            'pagination' => [
                'total' => $warga->total(),
                'per_page' => $warga->perPage(),
                'current_page' => $warga->currentPage(),
                'last_page' => $warga->lastPage(),
            ],
        ], 200);
    }```

This the route
```Route::get('/warga/search', [AppHttpControllersCivilliantController::class, 'search']);

i have try to debug at console and idk why my method return a blank page or somethimes 419 expired

Using specific Google font globally for Next.js project working only for default / route

I want to make ‘Roboto’ global font for my Next.js project. Here is my main layout file where I was trying to make it accoding to documentation.

import type { Metadata } from "next";
import { Roboto } from "next/font/google";

import "./globals.scss";

const roboto = Roboto({
  weight: "400",
  subsets: ["latin"],
  variable: "--font-roboto",
  display: "swap",
});

export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body className={roboto.className}>{children}</body>
    </html>
  );
}

Here is my global.scss file

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: var(--font-roboto);
}

I also have this component for login route (src/pages/login/index.tsx)

const Login = () => {
    return <button>Random button</button>
};

export default Login;

and when I’m adding this line:

import '../../app/globals.css';

all is working. But I don’t want to import global.css file in every file. I want import in just once in main leyout file and thats all.

Using specific Google font globally for Next.js project is not working

I want to make ‘Roboto’ global font for my Next.js project. Here is my main layout file where I was trying to make it accoding to documentation.

import type { Metadata } from "next";
import { Roboto } from "next/font/google";

import "./globals.scss";

const roboto = Roboto({
  weight: "400",
  subsets: ["latin"],
  variable: "--font-roboto",
  display: "swap",
});

export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en">
      <body className={roboto.className}>{children}</body>
    </html>
  );
}

Here is my global.scss file

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: var(--font-roboto);
}

But it just not working.

Google Maps Marker component does not register in Vue devtools

I have a Laravel app the renders pages through Inertia. I am trying to create a map with markers using Vue components. I render the Map.vue page through Inertia which serves as the view. The map and their markers are in separate Vue components.

I have a Map.vue page, a GoogleMap.vue and a GoogleMapMarkers.vue. GoogleMapmarkers.vue is a child component. The Map.vue page is rendered through the Laravel Inertia component.

The map loads but the markers do not. The markers components ony has Javascript, with no template or styles. When I open up Vue Devtools, I notice the GoogleMapMarkers component does not show up at all in my Devtools.

In addition, my my browser console, I get these error messages:

[Vue warn]: Unhandled error during execution of scheduler flush. This
is likely a Vue internals bug. Please open an issue at
https://github.com/vuejs/core . at <GoogleMap config= {zoom: 12,
center: {…}, mapTypeId: ‘roadmap’}
apikey=”AIzaSyCEzkHJy14pAJ-3yv9c9AxsyaexOnfopG0″ > at <Map errors=
{} auth= {user: null} ziggy= {url: ‘http://rideshare.test’, port:
null, defaults: Array(0), routes: {…}, location:
‘http://rideshare.test/map’} … > at <Inertia initialPage=
{component: ‘Map/Map’, props: {…}, url: ‘/map’, version:
‘7c81608be3d1be24c3ee4251df2359fa’, scrollRegions: Array(0), …}
initialComponent= {components: {…}, __hmrId: ‘2202ba0b’, __file:
‘C:/Code/laravel-projects/rideshare/resources/js/Pages/Map/Map.vue’,
data: ƒ, render: ƒ, …} resolveComponent=fn … > at
warn$1 @ chunk-KRQ7UQDJ.js?v=216d8c59:1512 logError @
chunk-KRQ7UQDJ.js?v=216d8c59:1724 handleError @
chunk-KRQ7UQDJ.js?v=216d8c59:1716 callWithErrorHandling @
chunk-KRQ7UQDJ.js?v=216d8c59:1661 flushJobs @
chunk-KRQ7UQDJ.js?v=216d8c59:1873 Promise.then (async) queueFlush @
chunk-KRQ7UQDJ.js?v=216d8c59:1782 queueJob @
chunk-KRQ7UQDJ.js?v=216d8c59:1776 (anonymous) @
chunk-KRQ7UQDJ.js?v=216d8c59:7591 resetScheduling @
chunk-KRQ7UQDJ.js?v=216d8c59:517 trigger @
chunk-KRQ7UQDJ.js?v=216d8c59:655 set @
chunk-KRQ7UQDJ.js?v=216d8c59:777 set @
chunk-KRQ7UQDJ.js?v=216d8c59:4585 (anonymous) @ GoogleMap.vue:28
invokeCallback @ google-maps-api-loader.js?v=216d8c59:292 publish @
google-maps-api-loader.js?v=216d8c59:281 flush @
google-maps-api-loader.js?v=216d8c59:95 characterData (async)
(anonymous) @ google-maps-api-loader.js?v=216d8c59:74 asap2 @
google-maps-api-loader.js?v=216d8c59:40 fulfill @
google-maps-api-loader.js?v=216d8c59:248 handleMaybeThenable @
google-maps-api-loader.js?v=216d8c59:211 resolve @
google-maps-api-loader.js?v=216d8c59:230 resolvePromise @
google-maps-api-loader.js?v=216d8c59:318
window.googleMapsAutoCompleteAPILoad @
google-maps-api-loader.js?v=216d8c59:594 (anonymous) @
js?key=AIzaSyCEzkHJy14pAJ-3yv9c9AxsyaexOnfopG0&callback=googleMapsAutoCompleteAPILoad:231
(anonymous) @
js?key=AIzaSyCEzkHJy14pAJ-3yv9c9AxsyaexOnfopG0&callback=googleMapsAutoCompleteAPILoad:231
Promise.then (async) hca @
js?key=AIzaSyCEzkHJy14pAJ-3yv9c9AxsyaexOnfopG0&callback=googleMapsAutoCompleteAPILoad:230
google.maps.Load @
js?key=AIzaSyCEzkHJy14pAJ-3yv9c9AxsyaexOnfopG0&callback=googleMapsAutoCompleteAPILoad:14
(anonymous) @
js?key=AIzaSyCEzkHJy14pAJ-3yv9c9AxsyaexOnfopG0&callback=googleMapsAutoCompleteAPILoad:408
(anonymous) @
js?key=AIzaSyCEzkHJy14pAJ-3yv9c9AxsyaexOnfopG0&callback=googleMapsAutoCompleteAPILoad:408
Show 22 more frames Show less chunk-KRQ7UQDJ.js?v=216d8c59:9625
Uncaught (in promise) TypeError: Cannot read properties of null
(reading ‘insertBefore’)
at insert (chunk-KRQ7UQDJ.js?v=216d8c59:9625:12)
at processFragment (chunk-KRQ7UQDJ.js?v=216d8c59:7257:7)
at patch (chunk-KRQ7UQDJ.js?v=216d8c59:6769:9)
at patchBlockChildren (chunk-KRQ7UQDJ.js?v=216d8c59:7185:7)
at patchElement (chunk-KRQ7UQDJ.js?v=216d8c59:7077:7)
at processElement (chunk-KRQ7UQDJ.js?v=216d8c59:6926:7)
at patch (chunk-KRQ7UQDJ.js?v=216d8c59:6783:11)
at ReactiveEffect.componentUpdateFn [as fn] (chunk-KRQ7UQDJ.js?v=216d8c59:7553:9)
at ReactiveEffect.run (chunk-KRQ7UQDJ.js?v=216d8c59:435:19)
at instance.update (chunk-KRQ7UQDJ.js?v=216d8c59:7597:17)

Map.vue

<template>
      <google-map
        :config="mapConfig"
        apikey="AIzaSyCEzkHJy14pAJ-3yv9c9AxsyaexOnfopG0">
        <GoogleMapMarkers :markers="mapMarkers"/>
      </google-map>
     
  </template>
  
  <script>
  import GoogleMap from '@/Components/GoogleMap.vue';
  import GoogleMapMarkers from '@/Components/GoogleMapMarkers.vue';


  export default {
  components: {
    GoogleMap,
    GoogleMapMarkers,
  },
  data() {
    return {
      mapConfig: {
        zoom: 12,
        center: {
          lat: -6.1753871,
          lng: 106.8249641
        },
      },
      mapMarkers: [
        {
          name: 'GBK',
          lat: -6.218605,
          long: 106.802612,
        },
        {
          name: 'Ancol',
          lat: -6.1229209,
          long: 106.8228804,
        },
        {
          name: 'Monas',
          lat: -6.1753871,
          long: 106.8249641,
        }
      ],
    };
  }
}

</script>
  
  <style>
  html,
  body {
    margin: 0;
    padding: 0;
  }
  </style>

GoogleMap.vue

    <template>
  <div id="map">
    <!-- Suspend mount children until google or map value is valid. -->
    <template v-if="google && map">
      <slot/>
    </template>
  </div>
</template>

<script>
import GoogleMapsApiLoader from 'google-maps-api-loader';

export default {
  props: {
    config: Object,
    apikey: String,
  },
  data() {
    return {
      google: null,
      map: null,
    }
  },
  mounted() {
    GoogleMapsApiLoader({
      apiKey: this.apikey
    }).then((google) => {
      this.google = google;
      this.initMap();
    }).catch(error => {
      console.error('Error loading Google Maps API:', error);
    });
  },
  methods: {
    initMap() {
      
      if (this.google && this.google.maps) {
        const mapContainer = this.$el;
        const { Map } = this.google.maps;
        this.map = new Map(mapContainer, this.config);;
      } else {
        console.error('Google Maps API or Map constructor is not available.');
      }
    },
  },
}
</script>

<style>
#map {
  height: 100vh;
  width: 100%;
}
</style>

GoogleMapMarkers.vue

<script>
export default {
  props: {
    markers: Array,
  },
  computed: {
    map() {
      return this.$parent.map;
    },
    google() {
      return this.$parent.google;
    },
  },
  mounted() {
    try {
      console.log(this.$parent.$el);
    this.markers.forEach(marker => {
      const { Marker, LatLng } = this.google.maps;
      new Marker({
        title: marker.name,
        position: new LatLng(marker.lat, marker.long),
        map: this.map,
      });
    });
  } catch(error) {
      console.log(error);
  }
  },
  render() {
    return null;
  },
}
</script>

app.js

import './bootstrap';
import '../css/app.css';

import { createApp, h } from 'vue';
import { createInertiaApp } from '@inertiajs/vue3';
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';
import { ZiggyVue } from '../../vendor/tightenco/ziggy';

const appName = import.meta.env.VITE_APP_NAME || 'Laravel';

createInertiaApp({
    title: (title) => `${title} - ${appName}`,
    resolve: (name) => resolvePageComponent(`./Pages/${name}.vue`, import.meta.glob('./Pages/**/*.vue')),
    setup({ el, App, props, plugin }) {
        return createApp({ render: () => h(App, props) })
            .use(plugin)
            .use(ZiggyVue)
            .mount(el);
    },
    progress: {
        color: '#4B5563',
    },
});

I have made sure my Google API billing settings are turned on. I am not sure if inertia is causing any of this. Hnestly, I don’t understand the error message. I have been dealing with this all day. Any help is appreciated

Load time of package.json?

Working with a node repl and tryihng this:

process.chdri('M://source/MySite')
let queries = await import('./src/graphql/queries.js')

Result is this:

export const getCompanySingleTable = /* GraphQL */ `
^^^^^^

Uncaught SyntaxError: Unexpected token 'export'

In ‘M://source/MySite/’ there is a package.json that contains the line:

    "type": "module",

I’m guessing the error is occurring because the package.json isn’t being read as the closest one. This raises the question,

When in package.json loaded?

Is it looked for when my repl is started? Is it looked for when when I try the dynamic import?

Is there a standard way to handle network errors and blocked requests across browsers?

According to the fetch spec https://fetch.spec.whatwg.org/#concept-network-error network errors responses should have status 0. But for these error cases we see the browser implementation of the fetch API throw a generic error. When I block a request in browser dev tools across any major browser I get a thrown error from fetch. The error message differs across browsers.

It surprises me that this behavior isn’t standardized. This is a big problem for our team’s telemetry and alerts. We want to filter out “network errors” from server errors when alarming our on call. We’ve resorted to string matching on the different set of error messages thrown across browsers. So far we have:

const NETWORK_OR_FIREWALL_ERROR_MESSAGES = [
  'TypeError: Failed to fetch', // Chrome
  'Failed to fetch', // Chrome, Edge
  'NetworkError when attempting to fetch resource.', // Firefox
  'Load failed', // iOS Safari,
];

I’m sure it’s not comprehensive – we have to incrementally add to this as our oncall engineer gets paged and then greps through logs.

Is there a better way to filter out network errors or is resorting to string matching on Error.message our best bet? Shouldn’t this be standardized so that fetch API across browsers throw a certain error type / message or is there a good reason it can’t be?

how can I use fetched data from firebase to create a pdf document using javascript, nodejs and pdfkit?

I’m working on automating the generation and download of loan agreements as PDF documents. The data for these agreements comes from two parties, “borrower” and “lender,” stored in a Firebase Realtime Database. My Firebase integration is working smoothly, fetching and displaying the stored data as intended. However, I’m facing some challenges in utilizing this data to create a PDF document using Node.js and pdfkit.

Here’s the setup: I have two JavaScript files to manage different aspects of the process. One handles the logic for fetching the data and other related operations, while the other is responsible for creating the PDF file using the fetched data.

However, I’ve encountered an issue where the terminal throws an error, stating that “Export ‘firebase’ is not defined in module,” even though Firebase is defined and imported correctly in the root file.

Here’s the relevant part of my code:

// myapprovedloan-details.js

// Function to fetch loan data for a specific user and loan
export function fetchLoanData(userID, loanID) {
    // Ensure that both userID and loanID are valid strings
    if (!userID || !loanID) {
        console.error('Invalid userID or loanID.');
        return;
    }

    // Construct the database reference path dynamically
    const loanDataRef = firebase.database().ref(`myApprovedLoans/${userID}/${loanID}/loanData`);

    // Fetch loan data from the database
    loanDataRef.once('value', (snapshot) => {
        const loanData = snapshot.val();
        if (loanData) {
            // Process loan data as needed
            console.log('Loan data:', loanData);
            // Call functions to update UI with loan data
            // Display loan information
            // Update other UI elements with loan data
        } else {
            console.error('No loan data found for loan ID:', loanID);
            // Handle the case where no loan data is found
        }
    });
// Export Firebase
export { firebase };
}

i’m fetching the lender’s data from the logged-in user.

    // Get the currently logged-in user
    const user = firebase.auth().currentUser;
    if (user) {
        const lenderID = user.uid; // Assuming user IDs are stored as UIDs in Firebase Authentication
        const userDataRef = firebase.database().ref(`myApprovedLoans/${userID}`);
        userDataRef.once('value', (snapshot) => {
            const userData = snapshot.val();
            if (userData) {
                // Start the lending flow
                showModal('startModal'); // Show the start modal
                // Pass the lenderID to moveLoanToMyApprovedLoans
                moveLoanToMyApprovedLoans(userData, lenderID);
            }
        });
    } else {
        console.log('No user logged in.');
    }
}

and the second code

// test.js

import pdfkit from 'pdfkit'; // Import the entire module
import fs from 'fs';
import { fetchLoanData } from './myapprovedloan-details.js';

// Generate a PDF document from the fetched loan data
const generatePDF = (loanData) => {
    // Create a new PDF document
    const doc = new pdfkit();

    // Pipe the PDF document to a file
    doc.pipe(fs.createWriteStream('loan-data.pdf'));

    // Draw the data on the PDF document
    doc.fontSize(25).text(loanData.name, 100, 100);

    // End the PDF document
    doc.end();
};

// Call fetchData function from myapprovedloan-details.js to start fetching loan data
fetchLoanData()
    .then((loanData) => {
        if (loanData) {
            generatePDF(loanData);
        }
    })
    .catch((error) => {
        // Handle the error
        console.error('Error fetching loan data:', error);
    });

Changing default value in input field React

I want to create an app on React where a user can input a number of his bank card. In the input field will be a default value with 16 zeros and every next zero will immediately change to the inputed number.

import React, { useState } from 'react'


function CardNumber() {
  const [value, setValue] = useState('')


  const changeState = event => {
    setValue(event.target.value)
  }


  return (
    <input
    value={value}
    onChange={changeState}
    placeholder='0000 0000 0000 0000'/>
  )

}

export default CardNumber