How to import only required functions/classes from Handlebars

I am using Handlebars in an Angular application and currently I have imported it as import * as Handlebars from 'handlebars'; But I want to import only required members of Handlebars such as import {registerHelper,compile} from 'handlebars';
It is working good with import * but when I try named imports, it gives me this error when I try testing the file-
enter image description here

Can anyone help me regarding this? I just want named imports to work. Lots of thanks in advance!
Handlebars version – 4.7.7
Angular version – 14.2.7

XPathEvaluator.evaluate does not wait element to get loaded

passing XPath of an element, to get element using XPathEvaluator.evaluate in javascript, It does not wait for element to be loaded, How to make it wait until element is loaded ?

var evaluator = new XPathEvaluator();

var result = evaluator.evaluate(path, document.documentElement, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);

As per above code it runs before element loads, and not able to get element, How to make it wait to get element everytime ?

Angular: Getting html parsing errors. Auto rendering some ‘_ng..’ empty attributes into the html

Angular: Getting html parsing errors. Auto rendering some ‘_ng..’ empty attributes into the html.

I am checking my angular generated html into ‘https://validator.w3.org/nu/’ html checker. I am getting WCAG-related parsing errors.

Errors for examples:

1) <a _ngcontent-ljv-c35="" class="innerlink">
2) <div _ngcontent-ljv-c35="" class="centered">

I tried code following code snippet in each component:

@component({
  selector: "app-test",
  templateUrl: "./test.component.html",
  styleUrls: ["./test.component.css"],
  encapsulation: ViewEncapsulation.None
})

But It is not solving above html parsing errors. Please suggest me solution for this.

Javascript, get information of other webpage, CORS problem

I am trying to develop a program that helps me to execute some basic tasks in my web browser. I made a short JavaScript, which allows me to open a webpage. To do this, I use:

window2 =window.open("URL","_blank"); 

Now I would like to access information like the URL of this page. For that I would like to use:

window2.document.URL; 

Now I always get the error
Permission denied to access property “document” on cross-origin object

I know that this is because I am not allowed accessing the information because of the cross-origin security. I tried to deactivate this by downloading the Allow CORS and the Moesif CORS extension in Firefox and Chrome, but it still doesn’t work.
I think its a very simple problem with an easy solution, but I really struggle to find it.

Here the full Javascrpit code:

const runBtn=document.getElementById('run');
let window2;

runBtn.addEventListener('click',async function(){

    window2 =window.open("https://www.google.com","_blank");
    
    console.log('start timer');
    await new Promise(resolve => setTimeout(resolve, 4000));
    console.log('after 4 second');
    console.log(window2.document.URL);

})

function delay(time) {
    return new Promise(resolve => setTimeout(resolve, time));
  }


and the html:

<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>

<button id="run">Run script</button>
<script src="test2.js"></script>
  
</body>
</html>

I would be so grateful if someone could help me. Best Regards!

I tried to deactivate this by downloading the Allow CORS and the Moesif CORS extension in Firefox and Chrome, but it still doesnt work.

How to call .Net Post Api with JavaScript

I’ve a .net endpoint which returns a jwt token like below
enter image description here

I tried to call this endpoint from JavaScript

  const response = await fetch("http://users:6400/api/authenticate/get_token", {
        method: 'POST',
        mode: 'cors',
        cache: 'no-cache',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            username: username,
            password: password,
            application_id:'44c5b142-6b05-4d29-98b3-5501ef71db0f',
            web_site:'WakeNC'
        })
    }).then((response) => {             
        if(response.ok) 
        {
            const myJson =  response.json();
             return response.json();               
        }
    }).catch((error) => {             
        console.log(error);
    });

here i’m getting success response, but I’m not able to read the token value
i’ve added the received response value below
enter image description here

let me know if anything I’ve to change, thanks

Chrome extension popup: fetch call in incognito mode

(1) I’m creating an extension that works with a website that requires a user log in.

(2) I’m trying to detect if the user is logged in or not, from the extension’s popup.

I can tell if the user is logged in or not by making a fetch call to specific URL, let’s say http://www.example.com/account, and what happens is:

  • If the account is logged IN, the fetch call is redirected to http://www.example.com/account/data.

  • If the account is logged OUT, the fetch call is redirected to http://www.example.com/login.

The problem is:

I do the fetch call from the extension’s content script and it works just fine, but, when I do it from inside the extension’s popup, there comes two scenarios:

(1) If I’m logging into the website in a normal window, the fetch call works just fine, it detects that I’m logging in and redirects me to http://www.example.com/account/data.

(2) But, if I’m NOT logging into the website in a normal window and instead logging into it in an incognito window, it does NOT detect my login and it always redirects the fetch call to the http://www.example.com/login page!


I was thinking maybe it has something to do with the website’s cookies, so, I tried to get the cookies, using the chrome.cookies API, and set them to the extension’s popup, but, this didn’t work!

Here is how I was trying to do it:

popup.js

chrome.cookies.getAll({
    domain: 'example.com'
}, function (cookies) {

    cookies.forEach(function (cookie, i) {
        // tried to set it this way, it didn't work: 
        chrome.cookies.set(cookie, function (savedCookie) {});

        // tried to set it to the `document.cookie`, as suggested here: 
        // https://stackoverflow.com/a/59620840/7607751
        // but, this didn't work either: 
        document.cookie = `${cookie.name}=${cookie.value}; `;
    });

    onAfterCookiesHandle();
});


function onAfterCookiesHandle() {
    console.log('document.cookie:', document.cookie);

    fetch(`https://www.example.com/account/`, {
        method: 'GET',
        credentials: 'include',

    }).then(function (response) {
        console.log('response:', response);
        if (response.url === `https://www.example.com/account/data`) {
            console.log('You are logged in, yay!');
        } else {
            console.log('You are logged out, oh no!');
        }

    }).catch(function (error) {
        console.error("HTTP fetch error:", error);
    });
}

PS. I’m enabling the extension to work with the incognito mode (from the extension’s settings), and in my manifest.json file I have the key: "incognito": "spanning".

What am I doing wrong here? and how can I get this to work in the incognito mode ?

Can I change the variable in a specific file and read it in another file in JavaScript?

Can I change the variable in a specific file and read it in another file in JavaScript?

While using Next.js, I have to set the cookie value in axios when sending a request from the backend, but I don’t want to put the cookie value as a factor every time, so after setting it up, I’m going to send a request only by calling a function.

So I implemented it through Closer, but the cookie value is stamped without any problems in the same file, but when importing from another file, the cookie value that I set is not stamped because it is newly created instead of a function that I previously created in memory.

So I implemented it through closures, but the cookie value is output without any problems in the same file, but the cookie value set when importing from another file is not output.

I put the code in the Codesandbox, so please check it.
You can access the test through https://4hos49-3000.csb.app/api/test path 🙂

You can check the files below.

  • apis/index.ts
  • pages/api/test.ts
  • middleware.ts

It would be very helpful if you could tell me if there was anything wrong with the closure I implemented or if there was anything else that I could achieve my goal.
Thank you 🙂

Below are the codes.

  • apis/index.ts
import axios from "axios";

const backendFetcherCloser = (cookies?: string) => {
  const fetcher = axios.create({
    baseURL: process.env.NEXT_PUBLIC_BACKEND_API_URL,
    withCredentials: true,
    headers: {
      Cookie: cookies,
    },
  });

  return {
    setCookie: (_cookie: string) => (cookies = _cookie),
    getCookie: () => cookies,
    instance: () => fetcher,
  };
};

const backendFetcher = backendFetcherCloser();

export default backendFetcher;
import { NextRequest } from "next/server";
import backendFetcher from "./apis";

const middlewareAPI = async (req: NextRequest) => {
  backendFetcher.setCookie("test");
  console.log(backendFetcher.getCookie()); // The 'test' is output.
};

export const middleware = async (req: NextRequest) => {
  if (req.nextUrl.pathname.startsWith("/api")) {
    return await middlewareAPI(req);
  }
};

export const config = {
  matcher: [
    "/((?!_next|kakao|robots.txt|favicon.ico|apple-touch-icon.png|apple-touch-icon-precomposed.png).*)",
  ],
};
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from "next";
import backendFetcher from "../../apis";

type Data = {
  cookie: string | undefined;
};

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data>
) {
  // I expect the test to be printed out, but it does not.
  res.status(200).json({ cookie: backendFetcher.getCookie() })
}

Why some code in the function is been executed twice?

I’m completely new to javascript and I’m trying to build Rock, paper, scissor game. I’ve trouble with the score. In the function, I want that in case of victory, the score increments by one and, in case of draw the score stays the same.

Everything works pretty much fine but in case of victory the score increments by 2. Can anyone help me to figure out the problem? Thanks

let pcChoice= ["rock","paper","scissor"];
let pcSelection= "";//getComputerChoice(pcChoice);
let playerSelection="";//prompt().toLowerCase();
let playerScore=0;
let pcScore=0;

function getComputerChoice(pcChoice){
    pcChoice=pcChoice[Math.floor(Math.random()*pcChoice.length)];
    return pcChoice;
}

function round(playerSelection,pcSelection){
    if(playerSelection===pcSelection){
        return "Draw! Your weapons are the same";
    }else if(playerSelection==="rock"&& pcSelection==="paper"){
         pcScore=pcScore+1;
         return "You Lose!Paper beats Rock";
    }else if(playerSelection==="paper"&& pcSelection==="scissor"){
         pcScore=pcScore+1;
         return "You Lose!Scissor beats paper";
    }else if(playerSelection==="scissor"&& pcSelection==="rock"){
         pcScore=pcScore+1;
         return "You Lose!Rock beats Scissor";
    }else if(playerSelection==="paper"&& pcSelection==="rock"){
         playerScore=playerScore+1;
         return "You Win!Paper beats Rock";
    }else if(playerSelection==="scissor"&& pcSelection==="paper"){
         playerScore=playerScore+1;
         return "You Win!Scissor beats paper";
    }else if(playerSelection==="rock"&& pcSelection==="scissor"){
        playerScore=playerScore+1;
        return "You Win!Paper beats Rock";
    }else{
        return "there is a problem"  }


}


for(let cont=0;cont<5;cont++){
    playerSelection=prompt().toLowerCase(); 
    console.log(playerSelection);
    pcSelection=getComputerChoice(pcChoice);
    console.log(pcSelection);
    round(playerSelection,pcSelection);
    console.log(round(playerSelection,pcSelection));
    
    
}
console.log(playerScore,pcScore);

Firebase functions query db to see if username already exists

I’m new to Firebase and Javascript so sorry if the answer is obvious.

I’m creating a function that imports a username, email, and password and checks if they are valid.
For the username one of the things I want to check is if there is already a user with the same name.
To see this I need to query my Firestore DB. The users are in the collection users with a doc for each user.
I don’t know what to do.

This is what I have. (Only the relevant part of the code)

const functions = require("firebase-functions");
const admin = require("firebase-admin");

admin.initializeApp();

var db = admin.firestore();

exports.checkUserValid = functions.https.onCall((data) =>{

    const email = data.email;
    const username = data.username;
    const password = data.password;

    try {
    /*
    Rest of the function
    /*

    const snapshot = db.collection('users').where('username', '==', username).get();
        if(snapshot.size > 0){
          return {status: "failed", message: "Name already in use."};
        }
    
        return {status: "ok", message: "ok"};

}catch (error){
    console.log(error);
        return {status: "failed", message: "Server error. "+ error};
      }

I’ve tried multiple things but for some reason, it either tells me its ok or fails no matter the username.

Weird issue with `fetch`

Please help, I’m getting a very weird issue with js fetch.

I’m trying to fech this from a userscript (it’s public):
https://naurok.com.ua/api2/test/sessions/303532970

fetch("https://naurok.com.ua/api2/test/sessions/303532970/").then(x => x.json()).then(console.log);

But it only works in Firefox and only if HTTPS-only mode is enabled

fetching
https://naurok.com.ua/api2/test/sessions/303532970/
makes a redirect to
http://naurok.com.ua/api2/test/sessions/303532970
(notice the lack of https and “/”)
which works but serves the request over http, which gets blocked (Mixed content)

…But if the browser upgrades the redirected request to https instead of blocking (like in firefox https-only mode) it succeeds and returns the data:
Object { session: {…}, settings: {…}, document: {…}, questions: (10) […] }

Opening
https://naurok.com.ua/api2/test/sessions/303532970
in browser also works fine (No redirect, it loads directly!)

But requesting
https://naurok.com.ua/api2/test/sessions/303532970
with fetch causes it to fail, everything goes through but the API returs “false”
(Copying headers sent by browser doesn’t help, code prduced by devtools Network->Request->Copy->Fetch also fails)

How are these requests different? they look (almost) the same in DevTools.

(The API I’m working with is undocumented)

XMLHttpRequest not updating data

I have an html file with some javascript (NO jquery) that retrieves data from a server and stores it in a variable called sData_From_Server, which is shown on screen.

That data is saved in a file called DATA_BASE.txt, and it’s a simple list of words that the user can change and send back to be saved in the server.

This is the code that I use to get that data from the server:

var sData_From_Server, sData_Entered_By_User;

fRetrieve_Data("DATA_BASE.txt", fCallback);

function fRetrieve_Data_From_Server(sFile, fFunction){
    let httpRequest = new XMLHttpRequest;
    httpRequest.open("GET", sFile);
    httpRequest.onload = fFunction;
    httpRequest.send();
}

function fCallback(){
    sData_From_Server = this.response;
    console.log(sData_From_Server);
    sData_Entered_By_User = sData_From_Server;
}

sData_Entered_By_User initially assumes the value of the previous stored data, and the user can change it at will (actually, all he can do is change the order of those words in that list).

Once the user is done he sends his updated list back to the server, and this is the code I use:

function fSend_Data_To_Server() {
    let xhr = new XMLHttpRequest();
    xhr.open("GET", "SAVE_DATA.php?sData_To_Be_Saved_By_PHP_File="+sData_Entered_By_User);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == XMLHttpRequest.DONE) {
            console.log("responseText: " + xhr.responseText);
        }
    };
    xhr.send();
}

Everytime I run fSend_Data_To_Server() the file DATA_BASE.txt is updated in the server.

Everytime.
There’s NO error with this part of the code.

However, if I reload my page (or even if I close the browser and open it again) the content of sData_From_Server is not being updated.

I think there’s something going on about the browser’s cache, but I don’t undestand why it’s happening. I think it should not be happening.

Let’s say the content of DATA_BASE.txt is A,B,C,D,XXXXXXXXXX.

When I first load the page I got that content in the variable sData_From_Server and I put it on the screen. It works perfectly.

Let’s call it LIST ONE.

If I change that list to XXXXXXXXXX,A,B,C,D and send it to the server I can see that the content of DATA_BASE.txt is changed in the server. I do this checking through the server file manager.

Let’s call it LIST TWO.

This new list is in my sreen at this time, but if I reload the page and therefore running fRetrieve_Data(“DATA_BASE.txt”, fCallback); again, the variable sData_From_Server assumes the value of LIST ONE.

How come???

If a open a different browser I can retrieve the correct data from DATA_BASE.txt, and this second browser shows me LIST TWO, but if I change the list and send it to the server (let’s call it LIST THREE) this second browser won’t update to this third list.

That means I have the file “DATA_BASE.txt correectly updated with LIST THREE, but the first browser keeps showing LIST ONE and the second browser keeps showing LIST TWO.

How can it be???

Even if I edit the file DATA_BASE.txt directly in the server and reload my browsers none of them will show me the right content at this time.

If I rename DATA_BASE.txt (on the server) to whatever other name, and then change througout the code to this new file name than I finally get the last list sent on screen (LIST THREE).

How come fRetrieve_Data_From_Server can not read the file on the server and get its content properly everytime???

How to use javascript to achieve the following photo wall function?

Many rows and many columns of multiple photos are displayed on a large screen. When one of the photos is clicked, the clicked photo will be enlarged and displayed. With the center of this photo as the radius, a circle is formed, and other photos close to this photo are shrunk to the outside of the circle.
After closing this photo, all photos will be restored to their original state.

Is there some javascript library that can facilitate this function?

Thank you so much.

Figure 1: Initial state without clicking any photos

Figure 2: After clicking a photo, the surrounding photos start to shrink, and the clicked photo starts to zoom in

Figure 3: The clicked photo is enlarged, and the surrounding photos are shrunk out of the circle

Here is the example video. http://www.touchf.com/temp/1.mp4