React app doesn’t recognizes NodeJs Backend

I have a react js app initialized with vite and I want to add a Node.js backend, however I can’t, and when I add the index.js and run the command it only initializes the react and doesn’t recognize posts and express routes. Can anybody help me? This is my App.jsx and my index.js:

App.jsx (it is initialized by main.jsx, but it is just vite code):

import { ResolutionList } from "./components/resolutions/ResolutionList";
import { ResolutionForm } from "./components/resolutions/ResolutionForm";
import {BrowserRouter as Router,Route, Routes as Switch} from "react-router-dom";
import { SearchBar } from "./components/search/SearchBar";
import {Login} from "./components/screens/Login";

function ShowResolutions() {
  return (
    <>
      <ResolutionForm />
      <ResolutionList />
    </>
  );
}

function App() {
  
  return (

  
    <>
      <Router>  
        <Switch>
          <Route path="/" element={<ShowResolutions />} />
          <Route path="/search" element={<SearchBar />} />
          <Route path="/login" element={<Login />} />
        </Switch>
      </Router>

      
    </>
  );
}

export default App;

The routes lead to react components that worked fine when I hadn’t added the NodeJs server.
index.js:

const express = require('express');
const app = express();
const path = require('path');
const cors = require('cors');
const { handleLogin } = require('./controllers/user.controller');
const bodyParser = require('body-parser');



app.use(cors());


app.use(express.static(path.join(__dirname, 'public')));


app.use(bodyParser.json());

app.set('port',process.env.PORT || 3000);



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



app.post('/api/login', handleLogin);

module.exports = app;

user.controller.js with the route to login:

const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());

const handleLogin = (req, res) => {
    const { username, password } = req.body;
    console.log("username: ", username, "password: ", password);
  };


module.exports = {
    handleLogin
}```

Improving code performance: Time limit exceeded

I wrote a solution for the HackerRank task “Climbing the Leaderboard” where you have an descending array (ranked) with existing scores and an ascending array of the player’s scores (player) and you are supposed to give back an array with the ranking of the player using the dense ranking.

My solution seems to be correct (no test cases have a wrong answer) but too slow. For 3 test cases I receive: Time limit exceeded.

I have already tried to make the implementation more efficient by:

  • breaking out of the for loop and add the ones once the player reached the first ranking (player is ascending, so all following rankings will be 1 as well)
  • using a pointer to avoid checking unnecessary values (since player is ascending and ranked descending)
    but it’s still not fast enough. Could someone give me advice on how to make my code faster? Also it’s kind of long. I am sure there is a shorter way to write it.

I am happy for any information on how to improve my solution.

const oneVector = n => [...Array(n)].map((x, i) => 1);

function climbingLeaderboard(ranked, player) {
  // Write your code here

  ranked = [...new Set(ranked)];
  let pointer;
  let ranking = [];
  let isFinished;
  let nextIndex;

  for (let i = 0; i < player.length; i++) {
    if (ranking[ranking.length - 1] === 1) {
      break;
    }
    pointer = nextIndex || ranked.length - 1;
    isFinished = false;
    // smaller than the smallest value
    if (i === 0 && player[i] < ranked[ranked.length - 1]) {
      ranking.push(ranked.length + 1);
      ranked = [...ranked, player[i]];
      isFinished = true;
      nextIndex = ranked.length;
    }
    //  bigger than the biggest value
    else if (player[i] > ranked[0]) {
      ranking.push(1);
      ranked = [player[i], ...ranked];
      isFinished = true;
      nextIndex = 0;
    }
    // exactly the first value
    else if (player[i] === ranked[0]) {
      ranking.push(1);
      isFinished = true;
      nextIndex = 0;
    }

    while (!isFinished) {
      // exactly the value
      if (player[i] === ranked[pointer]) {
        ranking.push(pointer + 1);
        isFinished = true;
        nextIndex = pointer;
      }
      // between values
      else if (player[i] > ranked[pointer] && player[i] < ranked[pointer - 1]) {
        ranking.push(pointer + 1);
        ranked = [
          ...ranked.slice(0, pointer),
          player[i],
          ...ranked.slice(pointer),
        ];
        isFinished = true;
        nextIndex = pointer;
      } else {
        pointer -= 1;
      }
    }
  }
  if (ranking.length < player.length) {
    ranking = [...ranking, ...oneVector(player.length - ranking.length)];
  }

  return ranking;
}

I have troubles running React

So I am just starting with learning React and I already have trouble using it (maybe i am just stupid but i ran through so many videos and solution but that still didn’t work). I am just trying to type “Hello World” in my document.

HTML:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test</title>
</head>
<body>

    
    
    <script type="text/babel" src="index.js"></script>    <!-- Also doesn't work with type="module" -->
</body>
</html>

JS:

import React from "react";

function Message() {
  return <h1>Hello world</h1>;
}

export default Message;

So i added module type to “package.json” under "version": "0.1.0", and that still didn’t work.
I don’t think if this is a problem but i made my files like this: Here’s image of files locations

I got a JQuery and don’t know how to convert it into JavaScript [duplicate]

my JQuery:

$('.menu').click (function(){
  $(this).toggleClass('open');
});
  
 
  $('.btn0').click(function() {
    if ($(this).hasClass("open")) {
      $('.drop-down').animate({top: "0px"}, 200);
      return;
    }
    $('.drop-down').animate({top: "-100vh"}, 200);
    
  });

the first line, I could convert into

document.querySelector(".menu").addEventListener("click", function() { 

but the $this is not really converable into JavaScript. what should I do indstead?

How do I remove Weekends & various days off in this Calendar?

I am creating a calendar for my son to count down the days until he out for school for summer. As I want to remove some weekends, I also want to remove a few service days that he will not be attending school. That said date is May 12th. Here is what I have so far:

<

    var deadline = new Date("May 25, 2023 15:00:00").getTime();

    var x = setInterval(function () {

        var now = new Date().getTime();
        var t = deadline - now;
        var days = Math.floor(t / (1000 * 60 * 60 * 24));
        var hours = Math.floor((t % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((t % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((t % (1000 * 60)) / 1000);
        document.getElementById("day").innerHTML = days;
        document.getElementById("hour").innerHTML = hours;
        document.getElementById("minute").innerHTML = minutes;
        document.getElementById("second").innerHTML = seconds;
        if (t < 0) {
            clearInterval(x);
            document.getElementById("demo").innerHTML = "TIME UP";
            document.getElementById("day").innerHTML = '0';
            document.getElementById("hour").innerHTML = '0';
            document.getElementById("minute").innerHTML = '0';
            document.getElementById("second").innerHTML = '0';

I have remove weekends in other ones I have done but not certain days of the calendar. Any help would be greatly appreciated!

Typescript – TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension “.ts”

I have this problem when I try to “firebase deploy”

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /workspace/src/index.ts
    at new NodeError (node:internal/errors:399:5)
    at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:79:11)
    at defaultGetFormat (node:internal/modules/esm/get_format:121:38)
    at checkSyntax (node:internal/main/check_syntax:58:26) {
  code: 'ERR_UNKNOWN_FILE_EXTENSION'
}

Node.js v18.15.0; Error ID: 037e0eb0

and I don’t know know to fix it.

My files are:

  • package.json
{
  "dependencies": {
    "axios": "^1.3.5",
    "firebase-admin": "^11.5.0",
    "firebase-functions": "^4.2.1",
    "nodemailer": "^6.9.1"
  }
}
  • tsconfig.json
{
  "compilerOptions": {
    "module": "CommonJS",
    "moduleResolution": "Node",
    "esModuleInterop": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "outDir": "lib",
    "sourceMap": true,
    "strict": true,
    "noImplicitAny": false,
    "target": "ES2022",
    "moduleDetection": "force"
  },
  "ts-node": {
    "esm": true,
    "experimentalSpecifierResolution": "node"
  },
  "compileOnSave": true,
  "include": [
    "src"
  ]
}

I am very happy if someone can help me to fix it. Thanks

I tryed to add in the package.json

"type": "module"

but nothing. Also to change in the tsconfig.json

"module": "ESNext" or "ES2023"

without success

How do I add a number that has an “animation” that shows it going up in JavaScript?

So, I am trying to make a random number generator with HTML and JavaScript. I want it to have a thing where it goes up by one until it reaches the random number so it has an “animation” of some sort, but I can’t make it work. Here is my code:

document.getElementById("numbergenerator").onclick = generateNumber;

function generateNumber() {
    numbervalue = Math.floor(Math.random() * 1001);
  for(var i = 0; i < numbervalue; i++) {
    setTimeout(goUpThing(i), 10);
  }
  document.getElementById("numberdisplay").innerHTML = numbervalue;
}

function goUpThing(number) {
    document.getElementById("numberdisplay").innerHTML = number;
}
<html>
  <body>
    <h1>
      <em>random stuff</em>
    </h1>
    <hr>
    <h2 id="numberdisplay">
      there is no number yet
    </h2>
    <div>
    <button id="numbergenerator" type="button">
      generate a random number
    </button>
    </div>
  </body>
</html>

Can someone please help me? By the way I am using JSFiddle to run my code.

How to convert timezones to determine availability?

I run a mentorship platform. I store the timezone of mentors in the following format America/New_York. I also store the time range they are available and the day. For example, Sundays between 1pm and 3pm. Users want to be able to filter mentors by day and time. So they would select a day like Thursday and time range like 1 pm to 6 pm that they want to meet a mentor.

Few questions

  • I’m getting the user’s timezone using Intl.DateTimeFormat().resolvedOptions().timeZone. How to I convert the time range (1pm to 3pm) that the user chooses to the mentor’s time zone and availability?

It’s a tricky problem that is hard to figure out. If you can help, I would appreciate it.

I’m using javascript, node, and React.

React Native app-release.apk not working as debug mode

When I ran npx react-naive run-android I can see the code I wrote getting implemented but when I run npx react-native run-android –variant=release it does not take my current code edits.

This is my build.gradle file:

apply plugin: "com.android.application"
apply plugin: 'com.google.gms.google-services'
import com.android.build.OutputFile
import org.apache.tools.ant.taskdefs.condition.Os

/**
 * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
 * and bundleReleaseJsAndAssets).
 * These basically call `react-native bundle` with the correct arguments during the Android build
 * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
 * bundle directly from the development server. Below you can see all the possible configurations
 * and their defaults. If you decide to add a configuration block, make sure to add it before the
 * `apply from: "../../node_modules/react-native/react.gradle"` line.
 *
 * project.ext.react = [
 *   // the name of the generated asset file containing your JS bundle
 *   bundleAssetName: "index.android.bundle",
 *
 *   // the entry file for bundle generation. If none specified and
 *   // "index.android.js" exists, it will be used. Otherwise "index.js" is
 *   // default. Can be overridden with ENTRY_FILE environment variable.
 *   entryFile: "index.android.js",
 *
 *   // https://reactnative.dev/docs/performance#enable-the-ram-format
 *   bundleCommand: "ram-bundle",
 *
 *   // whether to bundle JS and assets in debug mode
 *   bundleInDebug: false,
 *
 *   // whether to bundle JS and assets in release mode
 *   bundleInRelease: true,
 *
 *   // whether to bundle JS and assets in another build variant (if configured).
 *   // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
 *   // The configuration property can be in the following formats
 *   //         'bundleIn${productFlavor}${buildType}'
 *   //         'bundleIn${buildType}'
 *   // bundleInFreeDebug: true,
 *   // bundleInPaidRelease: true,
 *   // bundleInBeta: true,
 *
 *   // whether to disable dev mode in custom build variants (by default only disabled in release)
 *   // for example: to disable dev mode in the staging build type (if configured)
 *   devDisabledInStaging: true,
 *   // The configuration property can be in the following formats
 *   //         'devDisabledIn${productFlavor}${buildType}'
 *   //         'devDisabledIn${buildType}'
 *
 *   // the root of your project, i.e. where "package.json" lives
 *   root: "../../",
 *
 *   // where to put the JS bundle asset in debug mode
 *   jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
 *
 *   // where to put the JS bundle asset in release mode
 *   jsBundleDirRelease: "$buildDir/intermediates/assets/release",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in debug mode
 *   resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in release mode
 *   resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
 *
 *   // by default the gradle tasks are skipped if none of the JS files or assets change; this means
 *   // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
 *   // date; if you have any other folders that you want to ignore for performance reasons (gradle
 *   // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
 *   // for example, you might want to remove it from here.
 *   inputExcludes: ["android/**", "ios/**"],
 *
 *   // override which node gets called and with what additional arguments
 *   nodeExecutableAndArgs: ["node"],
 *
 *   // supply additional arguments to the packager
 *   extraPackagerArgs: []
 * ]
 */

project.ext.react = [
    enableHermes: true,  // clean and rebuild if changing
]

apply from: "../../node_modules/react-native/react.gradle"

/**
 * Set this to true to create two separate APKs instead of one:
 *   - An APK that only works on ARM devices
 *   - An APK that only works on x86 devices
 * The advantage is the size of the APK is reduced by about 4MB.
 * Upload all the APKs to the Play Store and people will download
 * the correct one based on the CPU architecture of their device.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = false

/**
 * The preferred build flavor of JavaScriptCore.
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US.  Note that
 * this variant is about 6MiB larger per architecture than default.
 */
def jscFlavor = 'org.webkit:android-jsc:+'

/**
 * Whether to enable the Hermes VM.
 *
 * This should be set on project.ext.react and that value will be read here. If it is not set
 * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
 * and the benefits of using Hermes will therefore be sharply reduced.
 */
def enableHermes = project.ext.react.get("enableHermes", false);

/**
 * Architectures to build native code for.
 */
def reactNativeArchitectures() {
    def value = project.getProperties().get("reactNativeArchitectures")
    return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
}

android {
    ndkVersion rootProject.ext.ndkVersion

    compileSdkVersion 33

    defaultConfig {
        applicationId "com.campuseats"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
        buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()

        if (isNewArchitectureEnabled()) {
            // We configure the CMake build only if you decide to opt-in for the New Architecture.
            externalNativeBuild {
                cmake {
                    arguments "-DPROJECT_BUILD_DIR=$buildDir",
                        "-DREACT_ANDROID_DIR=$rootDir/../node_modules/react-native/ReactAndroid",
                        "-DREACT_ANDROID_BUILD_DIR=$rootDir/../node_modules/react-native/ReactAndroid/build",
                        "-DNODE_MODULES_DIR=$rootDir/../node_modules",
                        "-DANDROID_STL=c++_shared"
                }
            }
            if (!enableSeparateBuildPerCPUArchitecture) {
                ndk {
                    abiFilters (*reactNativeArchitectures())
                }
            }
        }
    }

    if (isNewArchitectureEnabled()) {
        // We configure the NDK build only if you decide to opt-in for the New Architecture.
        externalNativeBuild {
            cmake {
                path "$projectDir/src/main/jni/CMakeLists.txt"
            }
        }
        def reactAndroidProjectDir = project(':ReactAndroid').projectDir
        def packageReactNdkDebugLibs = tasks.register("packageReactNdkDebugLibs", Copy) {
            dependsOn(":ReactAndroid:packageReactNdkDebugLibsForBuck")
            from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
            into("$buildDir/react-ndk/exported")
        }
        def packageReactNdkReleaseLibs = tasks.register("packageReactNdkReleaseLibs", Copy) {
            dependsOn(":ReactAndroid:packageReactNdkReleaseLibsForBuck")
            from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
            into("$buildDir/react-ndk/exported")
        }
        afterEvaluate {
            // If you wish to add a custom TurboModule or component locally,
            // you should uncomment this line.
            // preBuild.dependsOn("generateCodegenArtifactsFromSchema")
            preDebugBuild.dependsOn(packageReactNdkDebugLibs)
            preReleaseBuild.dependsOn(packageReactNdkReleaseLibs)

            // Due to a bug inside AGP, we have to explicitly set a dependency
            // between configureCMakeDebug* tasks and the preBuild tasks.
            // This can be removed once this is solved: https://issuetracker.google.com/issues/207403732
            configureCMakeRelWithDebInfo.dependsOn(preReleaseBuild)
            configureCMakeDebug.dependsOn(preDebugBuild)
            reactNativeArchitectures().each { architecture ->
                tasks.findByName("configureCMakeDebug[${architecture}]")?.configure {
                    dependsOn("preDebugBuild")
                }
                tasks.findByName("configureCMakeRelWithDebInfo[${architecture}]")?.configure {
                    dependsOn("preReleaseBuild")
                }
            }
        }
    }

    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include (*reactNativeArchitectures())
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://reactnative.dev/docs/signed-apk-android.
            signingConfig signingConfigs.debug
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }

    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // https://developer.android.com/studio/build/configure-apk-splits.html
            // Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc.
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        defaultConfig.versionCode * 1000 + versionCodes.get(abi)
            }

        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])

    //noinspection GradleDynamicVersion
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation "com.google.firebase:firebase-firestore-ktx"
    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
    implementation "com.google.firebase:firebase-storage-ktx"

    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.fbjni'
    }

    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }

    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }

    if (enableHermes) {
        //noinspection GradleDynamicVersion
        implementation("com.facebook.react:hermes-engine:+") { // From node_modules
            exclude group:'com.facebook.fbjni'
        }
    } else {
        implementation jscFlavor
    }
}

if (isNewArchitectureEnabled()) {
    // If new architecture is enabled, we let you build RN from source
    // Otherwise we fallback to a prebuilt .aar bundled in the NPM package.
    // This will be applied to all the imported transtitive dependency.
    configurations.all {
        resolutionStrategy.dependencySubstitution {
            substitute(module("com.facebook.react:react-native"))
                    .using(project(":ReactAndroid"))
                    .because("On New Architecture we're building React Native from source")
            substitute(module("com.facebook.react:hermes-engine"))
                    .using(project(":ReactAndroid:hermes-engine"))
                    .because("On New Architecture we're building Hermes from source")
        }
    }
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.implementation
    into 'libs'
}

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)

def isNewArchitectureEnabled() {
    // To opt-in for the New Architecture, you can either:
    // - Set `newArchEnabled` to true inside the `gradle.properties` file
    // - Invoke gradle with `-newArchEnabled=true`
    // - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true`
    return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true"
}

I dont know if there are any problems in my build.gradle which is not taking the current code.

Trying to add css into chrome extension

In attempting to learn more about chrome extensions, I am trying to create a few buttons to appear on a page. I originally used the setAttribute(“style”, “”) for them but I wanted to add something for a hover effect. So I created a style sheet and have been trying to inject it so that the styles will be picked up by the buttons. I have tried this in a myriad of ways:

First thing I saw was to put it into the content_scripts in the manifest.

Second I tried to add it to the web_accessible_resources and to append a link to the stylesheet to the webpage (from this answer Injecting custom CSS with content.js [CHROME EXTENSION] is not working)

Third I tried to utilize chrome.scripting.injectCSS but still no luck.

I’ve also tried different combinations of those but still nothing. The buttons I created are not taking in the css that I set for them.

Just for clarity, I set a class on the buttons and the css is selecting that class. All are labeled as !important as I saw that somewhere as well. I’m not quite sure what anyone would need to see to explain what it is I need to do in order to get these buttons to recognize the css that is being set for them in that file. Any help would be great and let me know if you need any snippets of my code

How do I make a chrome extension copy data to the users clipboard?

I’m trying to make a chrome extension that adds a context menu, which when pressed copies the highlighted text, link, image, etc.

This is the extension: https://chrome.google.com/webstore/detail/roll20-media-sender/lpmhjmhckammfiebfmimnjepibldfhjo and this is the github for the code: https://github.com/Rasul-583/Roll20-Media-Sender

I’m struggling with getting the app to actually copy the data. I keep getting the following error:

Error in event handler: TypeError: Cannot read properties of undefined (reading ‘writeText’) at chrome-extension://jijdnkfbchnjlimcackdbdcnknnbjnlk/background.js:34:25.

The extension doesn’t crash or anything, it “works” as in it launches and is generally functional, sending the notifications as intended. It just refuses to copy the data to the clipboard.

Here’s the js script:

chrome.runtime.onMessage.addListener( data => { // add a listener for incoming messages from the extension
  if ( data.type === 'notification' ) { // if the incoming message has a type of "notification"
    CBC( data.message ); // call a function CBC with the message from the data object as its argument
  }
});


chrome.runtime.onInstalled.addListener( () => { //code for context menu
  chrome.contextMenus.create({
    id: 'CBC',
    title: "Create Beyond20 Command", 
    contexts:[ "selection", "link", "image", "video" ]
  });
});


chrome.contextMenus.onClicked.addListener( ( info, tab ) => {//code for when context menu is pressed
  if ( 'CBC' === info.menuItemId ) {
    CBC( info.selectionText || info.linkUrl || info.srcUrl || 'error');
    navigator.clipboard.writeText( '[[after]]'+' [name]'+'('+info.selectionText+')[[/after]]'
    || '[[after]]'+' [name]'+'('+info.linkUrl+')[[/after]]'
    || '[[after]]'+' [name]'+'('+info.srcUrl+')[[/after]]' || 'error');
  }
} );


const CBC = message => { 
  return chrome.notifications.create( //code for notification system
    '',
    {
      type: 'basic',
      title: 'Command Created',
      message: '[[after]]'+' [name]'+'('+message+')[[/after]]' || 'error',
      iconUrl: './assets/icons/128.png',
    }
  );
};

I’ve searched for solutions extensively on the internet but haven’t found much. I tried simply making a test website with the same code to see if my code was fundamentally flawed but it worked perfectly so I just assumed it didn’t work because my extension wasn’t approved and published on the chrome webstore yet. This was not correct as it still is non-functional after publishing. Might have something to do with the new manifest v3? Not sure, am still a newbie dev.

Chrome extension MV3: contentPort.onMessage taking priority over nativePort.onMessage service worker

I’m migrating a MV2 extension to MV3 and as part of that process obviously switching to a background service worker.

My content script connects to the background service worker with the following API and then sets up some listeners on the port.

this.port = chrome.runtime.connect({name: CONTENT_BG_PROXY_CONNECTION_NAME});

In the service worker I register to listen for this connection and in response to that listen to messages on that port. I also then create my Native Messaging Host connection and listen for messages on that port as well (besides some additional busioness logci that I don’t think matters

chrome.runtime.onConnect.addListener(function(port) {

    if(port.name == CONTENT_BG_PROXY_CONNECTION_NAME) {
        let contentPort = port;

        let nativePort = chrome.runtime.connectNative(NATIVE_MESSAGING_APP_NAME);
        nativePort.onMessage.addListener(function(message) { 
            //...
            contentPort.postMessage(message);
        });

        contentPort.onMessage.addListener(function(message) {
            
            //...
            nativePort.postMessage(message);
            
        });
    }
});

The issue is if the content script is sending a lot of messages – worst case maybe 60 a second – then the contentPort.onMessage callback is continually triggered however the responses from the native host are not being processed as nativePort.onMessage is not being triggered.

Once I stop the content script sending messages all of a sudden all of those pending responses start being processed in nativePort.onMessage.

I’m sure there’s some rate limiting I can do or something, but this scenario worked perfectly with MV2. Processing seemed to be split between event handlers.

Is there a way to give equal priority to these event handlers, or in fact give higher priority to the messages coming back from the native host?

Content Security Policy blocking Google API for addon

I am writing an addon for Firefox and have problem with Content Security Policy. It needs accessibility to Google API when I press button on it, so I have added following script tag to popup.html

<script src="https://apis.google.com/js/api.js"></script>

However I had Content Security Policy errors. After many attempts I fixed it by just downloading api.js to addon folder and change to:

<script src="api.js"></script>

However, addon still connects with Google and is blocked by Firefox. Here are errors from dev-console:

Loading failed for the <script> with source “https://apis.google.com/_/scs/abc-static/_/js/k=gapi.lb[....]/cb=gapi.loaded_0?le=scs”. popup.html:1:1

Content Security Policy: The page’s settings blocked the loading of a resource at https://apis.google.com/_/scs/abc-static/_/js/k=gapi.lb[....]/cb=gapi.loaded_0?le=scs (“script-src”).

I tried to add necessary permissions in manifest file:

"permissions": [
  "...",
  "https://apis.google.com/"
],

Or tried to add meta data in popup.html’s like:

<meta http-equiv="Content-Security-Policy" content="
"content_security_policy": "default-src 'self'; script-src 'self' https://apis.google.com 'unsafe-eval';">

Or many other possibilities like:

script-src 'unsafe-inline';
default-src 'self';

Also tried with “nonce” attribute added to ‘script’ tag:

<script src="https://apis.google.com/js/api.js" nonce="random_value"></script>

and then

script-src 'self' https://apis.google.com 'nonce-random_value';

Or using wildcards like *.google.com

But all the time I have the same issue. I know that question was asked many times on StackOverflow but none of solutions worked for me. How can I manage to get it working? Thank you.

When import function from node module, why is module level code in the module also executed?

I have two .js files/modules in a node project. The module named “tester.js” imports an exported function from the “main.js” module. The “main.js” module also contains the module level code that runs when node runs the module: node main.js.

The unexpected behavior I see is that when I use node to run the “tester.js” module, the module level code of the “main.js” module also executes. This code executes when the “tester.js” module imports a function from the “main.js” module.

Is this expected behavior?

The output when node runs the “tester.js” module:

$ npm run tester

> [email protected] tester
> node ./tester.js

running main.js
tester.js start.
tester.js. add numbers result:60
// main.js
console.log(`running main.js`);

export function add_numbers( v1, v2 )
{
  return v1 + v2;
}
// tester.js
import { add_numbers } from "./main.js";

console.log(`tester.js start.`);
const res = add_numbers(25, 35);
console.log(`tester.js. add numbers result:${res}`);
{
  "name": "demo-import-from-main",
  "version": "1.0.0",
  "type": "module",
  "description": "demo that importing function from node module causes module level code to also run in the module.",
  "main": "./server.js",
  "scripts": {
    "main": "node ./main.js",
    "tester": "node ./tester.js"  
  }
}

Adding an array of objects into a nested object based on matching values. Javascript/React

i have a bigger nested object that has missing items i would like to fill from another array of object, by matching the ids from the bigger object and the small array of objects.

This is my orignal object:

data = {
        paints: {
          behr: {
            id: 'behr1',
            colors: {},
          },
          cashmere: {
            id: 'cashmere1',
            colors: {},
          },
        },
      }

Array of objects i would like to add to data object:

moreData = [
        0: {
          data: {
            lists: [{ // These go in the color section of the data object
              0: {
                id: 'behr1',
                tone: 'red',
              },
              1: {
                id: 'behr1',
                tone: 'blue',  
              },
              2: {
                id: 'behr1',
                tone: 'yellow',
              }
            }]
          }
        },
        1: {
          data: {
            lists: [{ // These go in the color section of the data object
              0: {
                id: 'cashmere1',
                tone: 'green',
              },
              1: {
                id: 'cashmere1',
                tone: 'purple',
              },
              2: {
                id: 'cashmere1',
                tone: 'orange',
              }
            }]
          }
        },
      ]

What i expect the new data object to look like, after matching ids and pusing moreData:

data = {
        paints: {
          behr: {
            id: 'behr1',
            colors: {
              0: {
                id: 'behr1',
                tone: 'red',
              },
              1: {
                id: 'behr1',
                tone: 'blue',
              },
              2: {
                id: 'behr1',
                tone: 'yellow',
              }
            },
          },
          cashmere: {
            id: 'cashmere1',
            colors: {
              0: {
                id: 'cashmere1',
                tone: 'green',
              },
              1: {
                id: 'cashmere1',
                tone: 'purple',
              },
              2: {
                id: 'cashmere1',
                tone: 'orange',
              }
            },
          },
        },
      }

Im assuming i will have to iterate through the moreData array to get to “lists” but how should i go about the whole thing. Thanks for your help