getting this error on a react native project and cant seem to even find it in my files?

this is the error as shown on the terminal, a quick note is that the app is “Android Bundling complete” not sure if it matters tho……
ERROR Invariant Violation: Failed to call into JavaScript module method AppRegistry.runApplication(). Module has not been registered as callable. Registered callable JavaScript modules (n = 11): Systrace, JSTimers, HeapCapture, SamplingProfiler, RCTLog, RCTDeviceEventEmitter, RCTNativeAppEventEmitter, GlobalPerformanceLogger, JSDevSupportModule, HMRClient, RCTEventEmitter.
A frequent cause of the error is that the application entry file path is incorrect. This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.
ERROR Invariant Violation: Failed to call into JavaScript module method AppRegistry.runApplication(). Module has not been registered as callable. Registered callable JavaScript modules (n = 11): Systrace, JSTimers, HeapCapture, SamplingProfiler, RCTLog, RCTDeviceEventEmitter, RCTNativeAppEventEmitter, GlobalPerformanceLogger, JSDevSupportModule, HMRClient, RCTEventEmitter.
A frequent cause of the error is that the application entry file path is incorrect. This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native.

i dont know where to start

Sending message on youtube live chat with chrome extension

I’m trying to add a button that can send a message to the live chat but I don’t think it’s finding the proper input element.

I added some logs to try and find it.

const sendMessage = (message) => {
  console.log('Sending message:', message);
  const chatInputBox = document.querySelector('#input');
  console.log('Chat input box:', chatInputBox);
  chatInputBox.focus();
  chatInputBox.innerText = message;
  chatInputBox.dispatchEvent(new Event('input', { bubbles: true }));
  setTimeout(() => {
    const sendButton = document.querySelector('#button');
    console.log('Send button:', sendButton);
    if (sendButton) {
      console.log('Clicking send button');
      try {
        sendButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));
      } catch (error) {
        console.error('Error sending message:', error);
      }
    } else {
      console.error('Could not find send button');
    }
  }, 1000);
};
};

content.js:42 Sending message: Hello!
content.js:44 Chat input box: <g id=​”input”>​<path d=​”M21 3.01H3c-1.1 0-2 .9-2 2V9h2V4.99h18v14.03H3V15H1v4.01c0 1.1.9 1.98 2 1.98h18c1.1 0 2-.88 2-1.98v-14c0-1.11-.9-2-2-2zM11 16l4-4-4-4v3H1v2h10v3z”>​​​
content.js:50 Send button: <button id=​”button” class=​”style-scope yt-icon-button”>​<yt-icon id=​”close-icon” icon=​”yt-icons:​close” class=​”style-scope ytd-miniplayer”>​…​​flex​
content.js:52 Clicking send button

[Android][WebView] Simple way to implement background media-playing

I have started building my own app to connect to my home media server with jellyfin.

The basic goal of this app is to allow the automation of enabling disabling VPNs and handling the IP’s to the server.
I got most of the things to work very well, even though it’s my first android app.
But if I turn the screen of my device off, or start another application on top the audio/video stops playing.
Is there any simple way to implement this?
Maybe if it is “easy” something like in Chrome itself would also be very nice: Popup on Chrome

As I read through the questions already asked about this topic i think i anyhow need to run the app as service, but have failed to get it to work.

webview audio play on background

MainActivity:

package com.example.jellyfin_beta;
 
import [needed stuff]
public class MainActivity extends AppCompatActivity {
 
        // private static final String HOME_WIFI_SSID = ""; 
    private static final String HOME_WIFI_IP_PREFIX = "192.168.1."; 
    private static final String SERVER_IP_HOME_WIFI = "http://192.168.1.111:8096/"; 
    private static final String SERVER_IP_VPN = "http://:8096/"; 
 
    private WebView webView;
    private View decorView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = findViewById(R.id.webview);
        webView.setWebViewClient(new WebViewClient());
        WebSettings webSettings = webView.getSettings();
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);
        checkNetworkAndLoadURL();
 
        decorView = getWindow().getDecorView();
        decorView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int visibility) {
                if (visibility == 0)
                    decorView.setSystemUiVisibility(hideSystemBars());
            }
        });
    }
        @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }
        @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            decorView.setSystemUiVisibility(hideSystemBars());
        }
    }
    private int hideSystemBars() {
        return View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
    }
    private class MywebClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }
    }
 
    @Override
    public void onBackPressed() {
        if (webView.isFocused() && webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }
 
    @Override
    protected void onDestroy() {
               super.onDestroy();
        Intent intent = new Intent("com.tailscale.ipn.DISCONNECT_VPN");
        intent.setClassName("com.tailscale.ipn", "com.tailscale.ipn.IPNReceiver");
        sendBroadcast(intent);
    }
    private void checkNetworkAndLoadURL() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
        if (activeNetwork != null && activeNetwork.isConnected()) {
            if (isConnectedToLocalNetwork()) {
                webView.loadUrl(SERVER_IP_HOME_WIFI);
            } else {
                Intent intent = new Intent("com.tailscale.ipn.CONNECT_VPN");
                intent.setClassName("com.tailscale.ipn", "com.tailscale.ipn.IPNReceiver");
                sendBroadcast(intent);
                webView.loadUrl(SERVER_IP_VPN);
            }
        } else {
            Toast.makeText(this, "No network connection", Toast.LENGTH_SHORT).show();
        }
    }
    private boolean isConnectedToLocalNetwork() {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface networkInterface = interfaces.nextElement();
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    if (!address.isLoopbackAddress() && address.getHostAddress().startsWith(HOME_WIFI_IP_PREFIX)) {
                        return true;
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return false;
    }
}

how can i make webview keep a video or audio playing in the background
This seems the most promising out of all threads to this topic, but i couldn’t get this to work.

Thank you for any help in advance.
And I please don’t explain too complicated, it’s my first time with android apps. 🙂

Import content from a plain text webpage as an array in JavaScript

I am trying to create an array of items in a JavaScript script from a webpage storing plain text data (raw.githubusercontent.com). Each item is on its own line on the webpage, and I want to load it into my Chrome extension’s content.js and create an array with each line from the webpage as item in the array. I can’t use any server-side code (no PHP, ASP, Node.js, etc.), the array needs to be loaded with JavaScript alone. What method would be best suited to do this?

I’d like to do some preprocessing on the data using regular expressions before it is turned into an array. Basically, I want to:

  1. Load the text from the webpage into my program.
  2. Process it via regular expressions.
  3. Convert it into an array, with each line being its own element in the array.

I’m not asking for help with step 2, I just want to know how to load the text and convert it into an array based on line breaks. The line breaks are Unix-style, i.e. n instead of carriage returns.

Why aren’t private static fields inherited like private instance fields?

From the MDN documentation:

There is a restriction on private static fields: Only the class which defines the private static field can access the field. This can lead to unexpected behavior when using this. In the following example, this refers to the SubClass class (not the BaseClassWithPrivateStaticField class) when we try to call SubClass.basePublicStaticMethod(), and so causes a TypeError.

class BaseClassWithPrivateStaticField {
  static #PRIVATE_STATIC_FIELD;

  static basePublicStaticMethod() {
    return this.#PRIVATE_STATIC_FIELD;
  }
}

class SubClass extends BaseClassWithPrivateStaticField {}

SubClass.basePublicStaticMethod(); // TypeError: Cannot read private member #PRIVATE_STATIC_FIELD from an object whose class did not declare it

[…]

You are advised to always access static private fields through the class name, not through this, so inheritance doesn’t break the method.

So private static fields aren’t inherited, which prevents using this in static methods. What is the benefit of that inheritance restriction?

On the contrary, private instance fields are inherited, which allows using this in instance methods:

class BaseClassWithPrivateInstanceField {
  #PRIVATE_INSTANCE_FIELD;

  basePublicInstanceMethod() {
    return this.#PRIVATE_INSTANCE_FIELD;
  }
}

class SubClass extends BaseClassWithPrivateInstanceField {}

new SubClass().basePublicInstanceMethod(); // undefined

Import JSON into index.html from exported constant from external .js

I’m sure this is an easy fix. I’m trying to use an external .js file to store a list of JSON objects stored as string constants (see form-json.js below).

These JSON objects should be able to be imported by name into an index.html file that loads a web component in which the JSON is passed to the web component as an input.

When I hardcode the JSON directly to a const inside a script block (without the type=”module” directive that’s required for importing modules) inside the index.html file it works great. However, I’m getting undefined when I try to load the same JSON block from the imported .js module. My code is below:

index.html

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Web Component!</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
    @import url('https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@400;700&family=Titillium+Web:wght@700&display=swap');
</style>
<link rel="stylesheet" href="styles.css"></head>
<body>
<my-form></my-form>
<script src="my-form.js" defer></script>
<script type="module">
    import {MY_SCHEMA_FORM} from './form-json.js';
    // alert('the schema form is:', UNITY_SCHEMA_FORM);
    let el = document.querySelector('my-form');
    el.formJson = UNITY_SCHEMA_FORM;
</script>
</body>
</html>

form-json.js

export const MY_SCHEMA_FORM = `{
    schema: {
    type: "object",
    title: "Remote API Call Example",
    description: "Makes an HTTP get using new getEndpoint() call",
    version: {
        created: "10.3.6",
        modified: "10.3.6"
    },
    size: "",
    properties: {
        "select-users": {
        type: "string"
        },
        "select-products": {
        type: "string"
        },
        brewery: {
        type: "string"
        }
    },
    required: [],
    rootWidgetClass: "  space-between",
    externalFieldsEvent: "",
    externalFieldsParams: [
        {
        paramName: "",
        paramValue: ""
        }
    ],
    htmlWrapperClass: ""
    },
    layout: [
    {
        allowOverride: true,
        appearance: "outline",
        defaultField: true,
        description: "https://jsonplaceholder.typicode.com/users",
        disabled: false,
        floatLabel: "always",
        htmlClass: "   ",
        id: "1678396918016",
        itemsLayoutWidth: " ",
        key: "select-users",
        mandatoryField: false,
        placeholder: "Select a user...",
        title: "JsonPlaceholder.com",
        title_revert: "getEndpoint",
        type: "select",
        wruxDynamic: true,
        wruxDynamicHook: "getEndpoint",
        wruxDynamicParams: [
        {
            name: "_endpoint",
            value: "jsonplaceholder.typicode.com/users"
        },
        {
            name: "_labelKey",
            value: "email"
        },
        {
            name: "_valueKey",
            value: "id"
        }
        ]
    },
    {
        allowOverride: true,
        appearance: "outline",
        defaultField: true,
        description: "https://dummyjson.com/products",
        disabled: false,
        floatLabel: "always",
        htmlClass: "   ",
        id: "1678399671572",
        itemsLayoutWidth: " ",
        key: "select-products",
        mandatoryField: false,
        placeholder: "Select a product...",
        title: "DummyJSON.com",
        title_revert: "Select",
        type: "select",
        wruxDynamic: true,
        wruxDynamicHook: "getEndpoint",
        wruxDynamicParams: [
        {
            name: "_endpoint",
            value: "dummyjson.com/products"
        },
        {
            name: "_labelKey",
            value: "title"
        },
        {
            name: "_valueKey",
            value: "id"
        }
        ]
    },
    {
        allowOverride: true,
        appearance: "outline",
        autocomplete: "off",
        dataType: "text",
        debounceCustomEventDelay: 0,
        defaultField: true,
        description: "https://api.openbrewerydb.org/breweries?by_city=birmingham",
        disabled: false,
        floatLabel: "always",
        panelWidth: " ",
        htmlClass: "   ",
        id: "1678400690595",
        itemsLayoutWidth: " ",
        key: "brewery",
        mandatoryField: false,
        placeholder: "Birmingham Breweries...",
        title: "API.OpenBrewery.org",
        title_revert: "getEndpoint",
        type: "text",
        wruxAutoCompleteHook: "getEndpoint",
        wruxAutoCompleteParams: [
        {
            name: "_endpoint",
            value: "api.openbrewerydb.org/breweries?by_city=birmingham"
        },
        {
            name: "_labelKey",
            value: "name"
        },
        {
            name: "_valueKey",
            value: "id"
        },
        {
            name: "_hiddenColumns",
            value:
            "id,  city, state, street, address_2, address_3,  county_province,  postal_code,  country,  longitude,  latitude,  updated_at,  created_at"
        }
        ]
    }
    ],
    data: {}
}`;

set variable to null is enough to free memory after a test?

I am reading stuff about test driven development. And I am reading about beforeEach() and afterEach() functions. In the following example variable containe is initialized. Used in beforeEach() and removed in afterEach(). Is this enough to free memory? Is enough set variables to null?

import { unmountComponentAtNode } from "react-dom";

let container = null;

beforeEach(() => {
  container = document.createElement("div");
  document.body.appendChild(container);
});

afterEach(() => {
  unmountComponentAtNode(container);
  container.remove();
  container = null;
});

I dont know instruments to see memory. Are there tool for this? To see that previusly allocated memory is now free? I know that in javascript, that hav its own garbage collector, is not necessary to free memory. Is this useless doubt?

How to do a x-www-form-urlencoded POST login using cypress?

I’m trying to build a direct API login using cypress. The app I want to test uses nextAuthJS (REST docs)

With postman I checked successfully the login POST request with this body as x-www-form-urlencoded:

username: 'user'
password: 'pass'
csrfToken: token // <= I recieved the token from `/api/auth/csrf` as a simple GET request.

And this is working, as next-auth.session-token cookie is created.

Now in my cypress test I tried to build up the same thing:

cy.request('/api/auth/csrf').then(({ body: { csrfToken } }) => {
  cy.request({
    method: 'POST',
    url: '/api/auth/callback/credentials',
    form: true,
    body: {
      username,
      password,
      csrfToken
    }
  }).then((res) => {
    cy.log(JSON.stringify(res))
  })
})

As you can see, I first do a GET request to recieve the csrf token. Then I use it in the post request, but I don’t get the session cookie in case of an successful login.

I’m not quite sure, if it is correct to use two nested then() and I don’t understand what I’m doing wrong as the postman request is working.

Why my function addMoedas( ) it’s not adding coins to the vault?

const cofre = [] 

The vault

const prompt = require('prompt-sync')() 

npm from the node that allows me to use a prompt to collect the inputs.

const menuPrincipal = () => {
    console.log('1 - Adicionar Moeda')
    console.log('2 - Remover Moeda')
    console.log('3 - Mostrar todas as moedas no cofre.')
    console.log('4 - Somar quanto dinheiro você tem.')
    const opcao = prompt('Selecione a sua opção: ')

    if (opcao > 0 && opcao < 5) {
        if (Number(opcao) === 1) {
            addMoedas()
        } else if (Number(opcao) === 2) {
            deleteMoeda()
        } else if (Number(opcao) === 3) {
            suasReservas()
        } else if (Number(opcao) === 4) {
            valorTotal()
        } else {
            console.log('Opção inválida!')
        }
    }
}

const addMoedas = () => {    

This function should read what kind of coin is inputted and its valor, adding it to the vault const cofre.

    const moedasAceitas = [5, 10, 25, 50, 100] 

The coins can’t differ from these values.

    console.log('1 - Real.')
    console.log('2 - Dólar.')
    console.log('3 - Euro.')
    const currency = prompt('Qual moeda você esta usando?')
    const valor = prompt('Qual o valor da moeda?')

    for (let i of moedasAceitas) {
        if (valor === i) { **>Is this conditional correct?<**
            switch (Number(currency)) {
                case 1:
                    cofre.push(valor)
                    console.log(`Você adicionou RS${valor} centavos ao seu cofre.`)
                    return cofre
                case 2:
                    valor = valor * 5
                    cofre.push(valor)
                    console.log(`Você adicionou $${valor} centavos ao seu cofre.`)
                    return cofre
                case 3:
                    valor = valor * 6
                    cofre.push(valor)
                    console.log(`Você adicionou ξ${valor} centavos ao seu cofre.`)
                    return cofre
                default:
                    console.log('Moeda inválida!')
            }
        }
        menuPrincipal() 

It should call the menu after the operation.

    }
    return cofre
}

Function to delete a coin from the vault.

const deleteMoeda = () => {
    const apagar = prompt('Qual moeda deseja apagar? ')
    for (let j of cofre) {
        delete apagar[j]
    }
    console.log(cofre)
    menuPrincipal()
    return cofre
}

const suasReservas = () => {
    console.log(cofre)
    menuPrincipal()
}
**Function to show how much money you gathered in your vault.**
const valorTotal = () => {
    const total = cofre.reduce((a, b) => a + b, 0)
    console.log(total)
    menuPrincipal()
}

menuPrincipal()

Agora Video SDK user-unpublished event get called for other remote users also

This is my useEffect code. I have subscribed to the user-joined, user-unpublished events. When multiple remote users join the channel, their video gets published successfully. When any of the remote user leaves the channel, all remote users get unpublished somehow.

useEffect(() => {
        let initClientCallbacks = () => {
            videoCallContext.client.on("user-published", async (remoteUser, mediaType) => {
                await videoCallContext.client.subscribe(remoteUser, mediaType);
                if (mediaType == "video") {
                    console.log("subscribe video success");
                    // remoteUser.videoTrack.play(document.getElementById("subscriber"));
                    setUsers((prevUsers) => {
                        return [...prevUsers, remoteUser];
                    });
                }
                if (mediaType == "audio") {
                    console.log("subscribe audio success");
                    remoteUser.audioTrack.play();
                }
                const p = document.getElementById('publisher');
                p.style.width = '30%';
                p.style.height = '30%';
                p.style.left = '10px';
                p.style.bottom = '10px';
            })





            videoCallContext.client.on("user-unpublished", async (user, type) => {
                if (user.uid === leavingUserUidRef.current) {
                    return;
                }

                console.log("unpublished", user, type);

                if (type === "audio") {
                    user.audioTrack?.stop();
                }

                if (type === "video") {
                    setUsers((prevUsers) => {
                        return prevUsers.filter((User) => User.uid !== user.uid);
                    });
                }

                setInitiatePolling(true);
            });

            videoCallContext.client.on("user-left", (user) => {
                console.log("leaving", user);
                console.log("leaving id", user.uid);
                leavingUserUidRef.current = user.uid;
                setUsers((prevUsers) => {
                    return prevUsers.filter((User) => User.uid !== user.uid);
                });
                setInitiatePolling(true);
            });


        }

        initClientCallbacks();

   
    }, [appointmentInformation?.id]);

I have tried to store leaving user id to make sure only that gets unpublished. But somehow, other remote users also get unpublished.

Google Tag Manager – Custom Javascript Variable returns undefined, stopping trigger

Im new to GTM and trying to create a custom javascript variable to return whether or not an action/event was in the footer or main body of the website. I want to use it to differentiate triggers in GTM like link clicks/form submit, etc.

Custom javascript variable code:

function() {
 var e = {{Form Element}};
 return e[0].indexOf("#footer");
}

On form submit shows up in the data layer as undefined:
Data layer Sceenshot

But if I take off the .indexOf("#footer") and try

function() {
 var e = {{Form Element}};
 return e[0];
}

It shows in the data layer as:
Data layer screenshot 2

So im not sure why .indexOf() wasn’t working but then If I try and change my trigger to us contains "#footer" logic in GTM it doesnt match.
Failed trigger screenshot

Im probably doing multiple things wrong. But I dont even know enough about GTM to know what question to ask.

Please help.

React Sticky Notes – How to update colour of only one note and not all notes

Using React I’m building a simple application for sticky notes where you can add as many sticky notes as you want.

I’m trying to add functionality to change the colour of the sticky note but it changes it for every sticky note present.

What can I do to my code below so that when I click the button, it only updates the sticky note in which I’m selecting the colour from?

I’m using state to update the colour but every sticky notes is affected by this.
I currently have a drop down menu from the sticky note that displays buttons (colours) I can select from.

const backgroundColors = [
{
color: “#FDFFB6”,
},
{
color: “#FFD6A5”,
},
{
color: “#FFADAD”,
},
{
color: “#CAFFBF”,
}
];

const [currentColor, setCurrentColor] = useState('#FDFFB6')

const setColor = (color) => {
setCurrentColor(color);
}

{backgroundColors.map((color, index) => (
<button
className="w-4 h-4 rounded-full mx-1"
style={{ background: color.color }}
onClick={() => setColor(color.color)}
>