Can’t open deep link from browser ( js )

When I try to executre window.open('nativecabinet://line/line_registration/70a4bd7d-b689-46fe-90e9-7fedc01b383f') , I get the issue :

line_registration:1 Failed to launch ‘nativecabinet://line/line_registration/70a4bd7d-b689-46fe-90e9-7fedc01b383f’ because the scheme does not have a registered handler.

It is enoying , but I can’t do anything. Tried to make it by link <a href="nativecabinet://line/line_registration/70a4bd7d-b689-46fe-90e9-7fedc01b383f">click</a> , it also doesn’t replace url in browser navigation bar . What I can I do with it ? I’ve found also that I can make my own scheme , by https://developer.mozilla.org/en-US/docs/Web/API/Navigator/registerProtocolHandler , but it only supported on 33% of devices , and it seems not the best idea to use it . I’m out of ideas .,,

How does the namespace of objects gets defined onto the ‘window’ object e.g. external dependencies via element?

How does the namespace of objects gets defined onto the ‘window’ object e.g. external dependencies via element?

I am using external dependencies distributed through CDN via the element. I don’t know what name to use to reference some of these dependencies so I console.log the window object to find it. What is happening behind the scene to cause it to name the React dependency as ‘React’, react-Dom as ‘ReactDOM’, or Babel as ‘Babel’?

I also noticed that some of the packages from the CDN’s had ‘import’ statements such as redux-toolkit which has import from 'immer', 'reselect', 'redux', 'redux-thunk' and export statements that ‘export * from "redux" and exports it’s own functions. Does this implies that there is some universal accepted naming convention for these libraries on the global scope? How can I find out what a CDN dependency via element is going to be named?

<!-- Babel (window.Babel) -->
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

<!-- react (window.React) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>

<!-- react-DOM (window.ReactDOM) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>

<!-- redux (window.Redux) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.2.1/redux.js"></script>

<!-- redux-toolkit (couldn't get it to show on window object) -->
<script src="https://cdn.jsdelivr.net/npm/@reduxjs/[email protected]/dist/redux-toolkit.legacy-esm.min.js"></script>

<!-- redux-thunk (couldn't get it to show on window object) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux-thunk/3.1.0/redux-thunk.legacy-esm.js"></script>
console.log(window):
{
Babel: {…}
React: {…}​
ReactDOM: {…}​
Redux: {…}​
_RTK: undefined​
_React: {…}​
_ReactRedux: undefined
​}

I have tried CDN sources and various versions to get all the dependencies to load properly on the project. I also downloaded each of the dependencies and searched through the code to see if there were code defining the namespace but did not find any. I would like to understand what determine how the namespace for that particular dependency gets named on the window object and how it goes about doing so.

NextJS API route ERR_TOO_MANY_REDIRECTS (no middleware)

I’ve been struggling to solve this problem for ages.

Occasionally my API routes calls are infinitely redirected and end up with error ERR_TOO_MANY_REDIRECTS. The only solution is to open the API URL manually, for a while the browser shows the redirect error, but after a few seconds, it successfully opens the API URL, and after that also the normal XHR API calls from the front end for a given URL start working again. Then the error repeats randomly after a few days. Every API URL must be “repaired” manually separately.

I’ve been searching all related information, but mostly when people had similar errors, they were using middleware and the error was happening consistently. For me, it happens once a day on localhost and once a week on Vercel production for my customers (which is really bad).

I have this same problem in NextJS v12.1.4 with /pages and NextJS v14.1.0 with /app folder.

I think that maybe something is wrong with Next itself, but I have no idea how to find the solution. When this error is happening, the actual API route is not even reached (I’ve tried to put console.log into GET, which normally is shown in the console, but when it’s being infinitely redirected, it happens even before the request hits the route. It is strange.

I’ve tried to add “trailingSlash: true” to next.config.js, no help. Maybe I could somehow disable caching on these API requests? They need to be fresh anyway.

enter image description here
enter image description here

mongoose getting when not using subdocument

When I log a user that I made with schema in mongoose, I get something named <Revoked Proxy>, so that I can not loop over this links array, or do anything to it

model {
  '$__': InternalCache {
    activePaths: StateMachine { paths: [Object], states: [Object] },
    skipId: true
  },
  '$isNew': false,
  _doc: {
    _id: ObjectId { [Symbol(id)]: [Buffer [Uint8Array]] },
    username: 'turmuka',
    password: 'asdf',
    email: '[email protected]',
    categoryLinks: [ [EmbeddedDocument], [EmbeddedDocument] ],
    links: <Revoked Proxy>,
    imagelink: '/images/blank',
    plan: '0',
    bakiye: 0,
    phoneNumber: 766951259,
    __v: 14
  }
}

The schema is as follows, only the links matter here,

const userSchema = new Schema({
  username: {
      type: String,
      unique: true
   },
  password: String,
  email: {
      type: String,
      unique: true
   },
  categoryLinks: {
    type: [categoryLinkSchema],
    validate: [function(doc) {
        for(let d of doc){
            const duplicates = this.categoryLinks.filter(function(c){
                return c.link === d.link || c.label === d.label;
            })
            if(duplicates.length > 1){
                return false;
            }
        }
    }, 'Each categoryLinks.label must be unique.']
  },
  links : { type : Array , "default" : [] },
  imagelink: String,
  plan: String,
  bakiye: Number,
  phoneNumber: Number
});

When I try to push something to the links array for the user, I try this but this seem not to be the correct,

  userModel.findOne({
    username: req.session.username
  }).then(
    (user) => {
      console.dir(user)
      res.render('takip-ettigim-indirimler', {links: user.links});
    }
  ).catch(
    (error) => {
      console.log('Error at login phase: ' + error.code + " error: " + error);
    }
  );

This seem to not work, so should I use [EmbeddedDocument] like I did with categoryLinks or is there a way to do it with just links : { type : Array , "default" : [] }, declaration?

Adding a Node.js back end to an existing React web app already deployed with Netlify?

What are some good resources to use and read for setting up a Nodes.js back end for my react application? I have tried searching but there aren’t many resources on adding it to an existing project that is deployed with just a front end. I honestly just didn’t see a back end coming to my project but now that it is finished, I want to add some features to it which would require a database and a back end.

Curious if there are any suggestions or advice to use. Thank you!

Getting interval is not a function error when using RxJS in Vanilla JS from a CDN

I’m currently learning RxJS using vanilla JS and loading RxJS (7.8.1) from a CDN. Most operators I’ve tried are working but when I try and use interval I get a “interval is not a function” error. I’m using the interval example from the docs and importing the operators following the directions from the docs as well. Here’s my Javascript code:

const { take, interval } = 'rxjs';

const numbers = interval(1000);
 
const takeFourNumbers = numbers.pipe(take(4));
 
takeFourNumbers.subscribe(x => console.log('Next: ', x));

And the HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://unpkg.com/rxjs@^7/dist/bundles/rxjs.umd.min.js"></script>
</head>
<body>
    <h1>RxJS Test</h1>
    <button id="myButton">Click Me</button>

    <script src="index.js"></script>
</body>
</html>

Is there a better way to import the operators?

How do I reauthenticate my logger after cookie expires

When first logging into my web application the logger is authenticated by setting the withCredentials parameter for AxiosRequestConfig to true. Here is the authentication class the logger uses to do that:

export class UserCredentialsAuth implements LogsRestAuthScheme {
    isWithCredentials = true

    public getAuthHeaders(): AxiosHeaders {
        return new AxiosHeaders()
    }
}

The logger works as expected for the first 15 minutes, but after that time the cookie expires and is refreshed. The issue is that withCredentials does not account for the refreshed cookie and the logger then proceeds to get 401 responses when attempting to post.

I’m not sure how to best go about resolving this. My application uses a node module that handles token refreshing, but I’m not sure how to use that in my logger node module.

Here is how to logger is initialized in my web application:

const logger = Logger.init({

    logIndex: "",
    authentication: new UserCredentialsAuth(),
    logDefaults: {
        appInstanceId: "",
        sessionId: sessionId,
        userId: "",
        appVersion: navigator.appVersion.match(/S*/)![0],
        os: (navigator as any).userAgentData
            ? (navigator as any).userAgentData.platform
            : navigator.userAgent,
        env: env,
    }

})

My best guess on how to approach this is to modify the authentication class to access the refreshed token and pass it to the headers somehow, but implementing that is where I’m confused.

Adding a listener to the Dailymotion Player event PLAYER_START when multiple players

I want to catch the event, when the users clicks on any Dailymotion video.

When there is only one video on the page, it is clear.

`// Get access to the embedded player instance using one of the get player methods. More info the    methods see here https://developer.dailymotion.com/player/
const callback = (state) => {
alert("Received PLAYER_START event");
}
dailymotion
.getPlayer()
.then((player) => {
// Add an event listener to the event 'PLAYER_START'
player.on(dailymotion.events.PLAYER_START, callback)
}).catch((e) => console.error(e));
`

But there are several videos.

Expo firebase: verifyBeforeUpdateEmail does not send email

I am trying to verify an email before being updated, with this code:

try {
    await verifyBeforeUpdateEmail(auth.currentUser, "[email protected]")
    [...code1]
} catch (e) {
    [...code2]
}

Even if code1 is called – as the function worked correctly – the verification email does not arrive.

Also, I do not know which email template is used by this function. I have four templates on firebase console:

  • Verify email address

  • Password reset

  • Email address edited

  • Sign up notification

My browser has no errors for localStorage

Well, I am on a school computer, so I can’t check the dev console. But I would like some help figuring out why this does not save to the localStorage.

var editor = document.getElementById('editor');
        var output = document.getElementById('output');
var textInput = document.getElementById('textSaveInput');
    var textOutput = document.getElementById('textSaveStat');
        editor.addEventListener('input', function() {
            output.innerText = editor.value;
        });

function saveTexteditor() {
    localStorage.setItem(textInput.value, editor.value);
    textOutput.innerHTML = "Saved as file " + textInput.value;
}

function loadTexteditor() {
    editor.value = localStorage.getItem(textInput.value);
    textOutput.innerHTML = "Loaded file " + textInput.value;
}

I tried running it through a compiler and it worked fine, but it does not work in the browser

Cannot start old project on mac, on win it works

npm i leads to following and i don’t know what to do with it
try reinstal node, python, pyenv and still have this issue
i’m using mac m1pro
the same node version on the windows run this project without issues
i’m stack with this issue and run the project, i don’t get it how it works on windows but on mac it crush

> [email protected] install /Users/nicetea/work/repos/planit-frontend/node_modules/node-sass
> node scripts/install.js

`Downloading binary from https://github.com/sass/node-sass/releases/download/v4.14.1/darwin-arm64-83_binding.node
Cannot download "https://github.com/sass/node-sass/releases/download/v4.14.1/darwin-arm64-83_binding.node": 

HTTP error 404 Not Found

Hint: If github.com is not accessible in your location
      try setting a proxy via HTTP_PROXY, e.g. `

      export HTTP_PROXY=http://example.com:1234

or configure npm proxy via

      npm config set proxy http://example.com:8080

> [email protected] postinstall /Users/nicetea/work/repos/planit-frontend/node_modules/node-sass
> node scripts/build.js


Building: /Users/nicetea/.nvm/versions/node/v14.21.3/bin/node /Users/nicetea/work/repos/planit-frontend/node_modules/node-gyp/bin/node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library=
gyp info it worked if it ends with ok
gyp verb cli [
gyp verb cli   '/Users/nicetea/.nvm/versions/node/v14.21.3/bin/node',
gyp verb cli   '/Users/nicetea/work/repos/planit-frontend/node_modules/node-gyp/bin/node-gyp.js',
gyp verb cli   'rebuild',
gyp verb cli   '--verbose',
gyp verb cli   '--libsass_ext=',
gyp verb cli   '--libsass_cflags=',
gyp verb cli   '--libsass_ldflags=',
gyp verb cli   '--libsass_library='
gyp verb cli ]
gyp info using [email protected]
gyp info using [email protected] | darwin | arm64
gyp verb command rebuild []
gyp verb command clean []
gyp verb clean removing "build" directory
gyp verb command configure []
gyp verb check python checking for Python executable "/opt/homebrew/bin/python3.10" in the PATH
gyp verb `which` succeeded /opt/homebrew/bin/python3.10 /opt/homebrew/bin/python3.10
gyp ERR! configure error 
gyp ERR! stack Error: Command failed: /opt/homebrew/bin/python3.10 -c import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack   File "<string>", line 1
gyp ERR! stack     import sys; print "%s.%s.%s" % sys.version_info[:3];
gyp ERR! stack                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
gyp ERR! stack SyntaxError: Missing parentheses in call to 'print'. Did you mean print(...)?
gyp ERR! stack 
gyp ERR! stack     at ChildProcess.exithandler (child_process.js:383:12)
gyp ERR! stack     at ChildProcess.emit (events.js:400:28)
gyp ERR! stack     at maybeClose (internal/child_process.js:1088:16)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:296:5)
gyp ERR! System Darwin 23.3.0
gyp ERR! command "/Users/nicetea/.nvm/versions/node/v14.21.3/bin/node" "/Users/nicetea/work/repos/planit-frontend/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
gyp ERR! cwd /Users/nicetea/work/repos/planit-frontend/node_modules/node-sass
gyp ERR! node -v v14.21.3
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok 
Build failed with error code: 1

Dynamic Routing in Vue.js, not found

I have this index.js file for routing and arranged /game/:game for dynamic routing.

import { createRouter, createWebHistory } from "vue-router";
import HomeView from "@/views/HomeView.vue";
import NotFound from "@/views/404.vue";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "home",
      component: HomeView,
    },
    {
      meta: { title: "Game Detail" },
      path: "/game/:game",
      name: "gameDetail",
      component: () => import("@/views/GameDetailView.vue"),
    },
    {
      meta: { title: "404" },
      path: "/:pathMatch(.*)*",
      name: "NotFound",
      component: NotFound,
    },
  ],
});

router.beforeEach(async (to, from, next) => {
  const title = to.meta.title || null;
  const appTitle = "GameApp";
  document.title = title ? `${title} | ${appTitle}` : appTitle;
  next();
});

export default router;

Also I added this .htaccess

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

But still, when I go domain.com/game/game_name, I got url not found error.

Should I use useEffect or useRef in order to achieve changing one operator to another in a calculator app built with React?

“I have a component that completes different types of calculation functions. I use the tag to render user inputs, but I can’t achieve the following: when the user types, for example, ’45+/’, I should change the ‘+’ operator to the ‘/’ operator in order to prevent consecutive input of operators.
I'll provide some snippets of my code

I've done this when the user uses buttons.

const handleDrawNumber = (input) => {
    const operators = ["/", "*", "+", "-", "%", "."];

    if (operators.includes(input)) {
      if (operators.includes(result[result.length - 1])) {
        setResult(result.slice(0, result.length - 1) + input);
      } else {
        setResult(result + input);
      }
    } else {
      setResult(result + input);
    }
  };

I've tried to resolve this issue when the user uses the keyboard.

useEffect(() => {
    console.log("RESULT: " + result);
    console.log("RESULT LENGHT: " + result.length);
    const operators = ["/", "*", "+", "-", "%", "."];
    const handleInput = (input) => {
      if (operators.includes(result[result.length - 1])) {
        const array = result;
        console.log("YES");
        setResult(array.slice(0, array.length - 1) + input);
      } 
    };

    handleInput();
  }, [result]);
////////////////////////////////////////
const handleFromKeyBoard = (input) => {
    setResult(input.target.value);
  };

How to change the key pressed in an input tag using dispatchEvent()? [ES6]

let’s say I have an html input and I would like that whenever someone press a key or combination of keys while the input is focused, it input a different character where the caret is positioned.

for instance let’s say I have a site with virtual keyboard French that is compatible with the English keyboard. But I also give the user the ability to use custom keyboard shortcut to input French characters (those with accent let’s say).

How would one do that using ES6’s dispatchEvent & KeyboardEvent Object?

Here is what I tried (the code uses JIS Layout Keyboard):

let isShiftPressed = false;
let isControlPressed = false;
let isNonConvertPressed = false;
let isConvertPressed = false;

const kbdDown = function(event) {
  if (event.code === "ShiftLeft" || event.code === "ShiftRight") {
    isShiftPressed = true;
  }
  if (event.code === "ControlLeft" || event.code === "ControlRight") {
    isControlPressed = true;
  }
  if (event.code === "NonConvert" || event.code === "NonConvert") {
    isNonConvertPressed = true;
  }

  console.log("{ code : " + event.code + ", key : " + event.key + "}");

  if (event.code === "KeyA" && isShiftPressed && isNonConvertPressed) {
    event.preventDefault();

    const keyPressedEvent = new KeyboardEvent("keydown", {
      key: "X",
      code: "KeyX"
    })

    event.target.dispatchEvent(keyPressedEvent);
  }
}

const kbdUp = function(event) {
  if (event.code === "ShiftLeft" || event.code === "ShiftRight") {
    isShiftPressed = false;
  }
  if (event.code === "ControlLeft" || event.code === "ControlRight") {
    isControlPressed = false;
  }
  if (event.code === "NonConvert" || event.code === "NonConvert") {
    isNonConvertPressed = false;
  }
}

const registerkbdHandler = function(element) {
  element.addEventListener("keydown", kbdDown);
  element.addEventListener("keyup", kbdUp);
}

registerkbdHandler(document.querySelector("input"));
<input type="text">

When I focus on the input field and press NonConvert + Shift + A it outputs the following on the browser console:

output-listing : console

{ code : NonConvert, key : NonConvert} script.js:21

{ code : ShiftLeft, key : Shift} script.js:21

{ code : KeyA, key : A} script.js:21

{ code : KeyX, key : X}

Clearly the keyboard event is getting dispatched but the input text field doesn’t show any new character.

How to update div A after div B has been swapped

I’m trying to figure out how to make this HTML structure work with htmx

<div id="optionscontainer" hx-get="http://localhost:8000/get_optionsview" hx-trigger="load"
  hx-swap="innerHTML" class="mb-5">
</div>
<div id="logincontainer" ...>
</div>

Every time the #logincontainer is updated, I’d like to also refresh the #optionscontainer. I think the right way would be to subscribe to events, here’s the code I’m using:

document.body.addEventListener('htmx:afterSwap', function (event) {
  if (event.target.id === 'logincontainer') {
    // this log message appears as expected
    console.log("should reload options now");
    // this query selector works as expected
    let optionsContainer = document.querySelector("#optionscontainer");
    console.log(optionsContainer);

    // this doesn't seem to do anything
    htmx.trigger("#optionscontainer", "htmx:refresh");
  }
});

For some reason, the htmx.trigger doesn’t have any effect. I’ve gone through various event names such as reload, refresh, etc.

Apart from that I think my routes work. Here’s how the website behaves:

  1. load website. There is a GET to the options route on the first page load, but then the options are supposed to still be absent, cause the user is not logged in. The placeholder is displayed correctly. So the GET to the options route is working. Click “login”, the “login” button is swapped out for “logout”. This also causes a bearer token to be set. Which I can see in the dev tools. The options are not reloaded.
  2. reload page. It’s still the “logout” button, the bearer token is of course still set. Now I see the correct options (reloading has sent a new GET request to the server). Click “logout”. The button is swapped for “login”, the bearer token is deleted. The options are not refreshed, no new GET request.
  3. jump back to step 1.

I’m also aware of the two other solutions that could be applicable here:

  • restructure the DOM layout, have the options be a child of the login container. But that would mess with separation of concerns on my server. I’d like to keep those routes separate. If I have the options template included in the login/logout template, then I need to fill in the options in that route.
  • OOB swap. That would allow me to keep the HTML on the client the same. But on the server I’d similarly have to deal with filling both the auth and options template in the same route.