Do something when a link is opened, no matter how i open it. (Angular project)

I have an Angular project and I need to save something to my cookies right before I open a link from <a>.

A click listener didn’t help as opening it with rightclick > open or Tab & Return wouldn’t work then.

Is there a way to check if the link was opened no matter in what way?

I was also thinking of using onunload or something similar but this would also fire when just leaving it through other ways.

String strangely mulfunctioning upon writing somewhere

I decide to write a simple script to generate a search line for a booru that looks like this:

(@lower artist | @lower another_artist | @lower e.t.c) & feral

For that i have a list of artists stored in separate file and lets say it looks like this:

artist another_artist e.t.c

So basically what my script doing is putting all this artists together with some adjustments covered by brackets and with & feral line at the end then write it to clipboard. Scripts code (sorry for uglyness):

import { writeText } from "https://deno.land/x/copy_paste/mod.ts";

const q=await Deno.open('./list of artists'),
w=new Uint8Array(1e5)
await q.read(w)
const e=new TextDecoder().decode(w).split(' ').map(v=>' @lower '+v).join(' |'),
r=`(${e}) & feral`
console.log(r)
writeText(r)

So my deno is up to date and i run the script with the next command (im on windows):

deno run -A "%~dp0my script.js"

Then console.log part of the code gives me exactly what i need:

( @lower artist | @lower another_artist | @lower e.t.c) & feral

But then in my clipboard i can find only this:

( @lower artist | @lower another_artist | @lower e.t.c

I tried to throw away external library and write my generated string directly into another file with this code:

const q=await Deno.open('./list of artists'),
w=new Uint8Array(1e5)
await q.read(w)
const e=new TextDecoder().decode(w).split(' ').map(v=>' @lower '+v).join(' |'),
r=`(${e}) & feral`
console.log(r)
Deno.open('./output.txt',{write:true}).then(v=>v.write(new TextEncoder().encode(r)))

But shockingly result was exactly the same: console gives me correct string but writed string was cut out.

My next thought was that im running out of memory somehow or something and tried to reduce the number of artists in the list:

artist_one artist_two

And even more shockingly again my line was cropped before this last ) & feral:

( @lower artist_one | @lower artist_two

And console still giving me the correct line:

( @lower artist_one | @lower artist_two) & feral

Adding more artists in the list instead of reducing them giving the same resault.

So after further experiments its simply doesnt matter how long the list and its doesnt matter what are you trying to write before and after this modified list, behaviour always the same: script write everything that is going before modified list (in our case its () then its write modified list (@lower artist | @lower another_artist | @lower e.t.c) and then its ommit everything after () & feral in our example). Im stunned and dont know whats happening. Some help?

I know javascript up to an intermediate level , but i don’t know how to proceed with the training [closed]

Honestly, I am writing the same text with Google Translate and I don’t know much English, so I thought this is where many experienced people can help me.
I spend about 12 hours a day learning JavaScript, but now that I am reading advanced material, I am very stressed because I know the concepts so far, but I have not done any practical exercises and projects, and I do not know English, and now I do not know if I should study English either Should I practice what I have learned so far and do a project or continue the same training or do all of them at the same time? I really don’t know what to do and I hope someone can help me

I tried to do all of them at the same time but I didn’t get any results and I feel like I shouldn’t read everything together

Python – Selenium – Windows vs Linux ( Add value to the Date picker)

The Main thing is that I try to add a date to the date field which is very easy:

  • Find Element / by using .send_keys("01/01/1990")

But the problem is that in Windows all working fine – and the date picker looks like this
enter image description here

But when I open it in a Linux box, the date picker opens like this (In the middle of the page with a shadow effect in the background) – which causes issues interacting with the input field:
enter image description here

Extra:

  • Windows and Linux execution happening in the headless mode
  • Both using the latest Chrome driver

What I have tried:

  • Using JS to remove this date picker, hide and etc…
  • using Actions / send_keys() and e.t.c…
  • Using JS to add value to the element (can add visually BUT when click on empty space date disappeared )

So, I have two questions:

  • Why is Windows and Linux date picker open differently
  • What will be the way to add the date to the Linux version date picker (straight to the input .. NOT by using the date picker itself)

I have 2 subsciptions on 2 different observables. If they are both “firing” at the same time i just want to execute 1 of them

I have 2 observable with a subscription on each of them. my problem is, if they fire at the same time, the code is influencing each other, so just the functionality of subscription 1 should be fired and sub 2 should be ignored.

this.windowRef.window.instance.resizeEnd
            .pipe(takeUntilDestroyed(this.destroyRef))
            .subscribe(() => {
                //...some code
            });

        this.windowRef.window.instance.stateChange
            .pipe(takeUntilDestroyed(this.destroyRef))
            .subscribe((state) => {
               //... some code
            });

i tried it to solf with rxjs zip, but came here to the problem i have to wait for all subscribe to fire until it triggers, so it won’t work there for me

javascript webrtc cancel negotiation

How can i cancel this webrtc function:

function negotiate() {
    return pc.createOffer({"offerToReceiveAudio":true,"offerToReceiveVideo":true}).then(function(offer) {
        return pc.setLocalDescription(offer);
    }).then(function() {
        // wait for ICE gathering to complete
        return new Promise(function(resolve) {
            console.log(pc.iceGatheringState);
            if (pc.iceGatheringState === 'complete') {
                resolve();
            } else {
                function checkState() {
                    console.log(pc.iceGatheringState);
                    if (pc.iceGatheringState === 'complete') {
                        pc.removeEventListener('icegatheringstatechange', checkState);
                        resolve();
                    }
                }
                pc.addEventListener('icegatheringstatechange', checkState);

            }
        });
    }).then(function() {
        var offer = pc.localDescription;
        
        return timeoutPromise(30000, fetch('/offer', {
            body: JSON.stringify({
                sdp: offer.sdp,
                type: offer.type,
                "name":name,
                "surname":surname
            }),
            headers: {
                'Content-Type': 'application/json'
            },
            method: 'POST'
        }));
    }).then(function(response) {
        return response.json();
    }).then(function(answer) {
        if (answer.sdp == "" && answer.type == ""){
            setTimeout(call_rejected, 1000);
            return null;
        }else{
            return pc.setRemoteDescription(answer);
        }
    }).catch(function(e) {
        //alert(e);
        console.log(e);
    });
    
}

It would be nice if i can stop it in any stage of running (for example terminating /offer request).

The code of timeoutPromise is:

function timeoutPromise(ms, promise) {
  return new Promise((resolve, reject) => {
    const timeoutId = setTimeout(() => {
      reject(new Error("promise timeout"))
    }, ms);
    promise.then(
      (res) => {
        clearTimeout(timeoutId);
        resolve(res);
      },
      (err) => {
        clearTimeout(timeoutId);
        reject(err);
      }
    );
  })
}

Maybe if i use a global boolean variable to reject every stage after an if statement is a solution but i am not familiar with javascript Promises (resolve – reject).

Issue with Angular12 while doing build with optimization=true

I have an issue in angular 12 in which I can’t seem to see where my errors are because they are not showing the component the error comes from but only show that it comes from main.js. This is a very confusing and makes it hard to solve issues.

I am getting Uncaught SyntaxError: Invalid regular expression flags (at main.5a123573fe857541fe05.js:1:1857379) only when doing ng build with optimization=true and unable to reproduce this issue on local.

Can you please help me on this?

enter image description here

How to get rid of this issue?

React Router: “Cannot read properties of null (reading ‘useRef’)” error

I am working on a React application with React Router, and I’m encountering an error that I can’t seem to resolve. The error message I’m getting is:

Uncaught runtime errors:
ERROR
Cannot read properties of null (reading 'useRef')
TypeError: Cannot read properties of null (reading 'useRef')

This error seems to be related to the usage of the useRef hook, but I’m not sure why it’s occurring. I’ve checked my code for any obvious issues with hooks or dependencies, but I can’t find the root cause.

Here is my code:


import React from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import SettingsPage from './components/settings'; // Import your Settings component

const App = () => {
  return (
    <Router>
      <div className="bg-gray-800 min-h-screen">
        <header className="py-4">
          <div className="container mx-auto flex justify-between items-center px-6">
            <Link to="/">
              <button className="bg-blue-600 text-white py-2 px-4 rounded">My New Taskboard</button>
            </Link>
            <nav>
              <ul className="flex space-x-4">
                {/* ... other buttons */}
                <li><button className="bg-blue-600 text-white py-2 px-4 rounded">Update</button></li>
                <li><button className="bg-blue-600 text-white py-2 px-4 rounded">Edit</button></li>
                <li><button className="bg-blue-600 text-white py-2 px-4 rounded">Open</button></li>
                <li><button className="bg-blue-600 text-white py-2 px-4 rounded">New</button></li>
                <li>
                  <Link to="/settings">
                    <button className="bg-blue-600 text-white py-2 px-4 rounded">Settings</button>
                  </Link>
                </li>
              </ul>
            </nav>
          </div>
        </header>

        <main className="container mx-auto p-6">
          <div className="grid grid-cols-4 gap-6">
            {[...Array(20)].map((_, i) => (
              <div key={i} className="bg-gray-700 h-40 rounded-lg"></div>
            ))}
          </div>
        </main>
      </div>

      {/* Route for the settings page */}
      <div>
        <Route path="/settings" component={SettingsPage} />
      </div>
    </Router>
  );
};

export default App;

I just want to make it when clicked on “Settings” button to route to the settings page, which I created as a component – settings.js.

I’m using React Router, and I have the necessary dependencies installed. I’ve also tried restarting my development server and clearing my browser cache, but the error persists.

If anyone has encountered a similar issue or has any insights into why this error might be occurring, I would greatly appreciate your help in resolving it. Thank you!

Video doesn’t appear on Chrome or Brave, but appears on Safari

I’ve been trying to make this video appear on chrome, but this just doesn’t work. No videos are showing up on chrome or brave at the moment, when I try to plug them in. However, they work on Safari pretty nicely. Why is that? What might be stopping this video to appear in Chrome?

<video playsinline="" loop="" muted="" autoplay="" style="background-image: url('');" data-wf-ignore="true" data-object-fit="cover">
  <source src="imgs/im/fin2.mp4" data-wf-ignore="true">
</video>

How do I access the element which haven’t been created yet in javascript?

I am completeing the Etch-a-Sketch project of TheOdinProject. I want to access the grid’s cell for changing it’s color, but they are created in the scope of a for() loop and that for() loop is inside the scope of a function. I’ve searched other questions and not getting what I want or maybe I cannot understand whatis being conveyed.

The function for creating grid

function changeGridSize(number) {
  let container = document.getElementById(`container`);
  totalNumber = number * number;
  while (container.hasChildNodes()) {
    container.removeChild(container.firstChild);
  }

  for (let i = 0; i < totalNumber; i++) {
    let gridSquare = document.createElement("div");
    gridSquare.classList.add("grid_square");

    let cellwidth = container.clientWidth / number + `px`;
    let cellheight = container.clientHeight / number + `px`;

    gridSquare.setAttribute(
      `style`,
      `width: ${cellwidth}; height: ${cellheight};`
    );
    container.appendChild(gridSquare);
  }
}

The code for changing color

let color = document.getElementById(`colour_picker`);
color.addEventListener(`change`, changeColor() );
let choosenColour = color.value;

function changeColor() {
  while (container.hasChildNodes()) {
    gridSquare.setAttribute(`style`, `background-color: ${choosenColour};`)
  }
}

When the user picks a color from the color picker the background color for the cells should change to that color which the user selected.
But when I add the change event listener to the color picker the page is crashing and also when I try to change the grid size above 40×40.

Exporting / Importing vanilla Javascript files after building does not render on html | Opposite of what occurs happens instead

This is the file I want to export

/* import IUrl from "../../interfaces/url.interface"; */

class BaseUrl {
  private static baseUrl: string = "http://localhost:53134";
  private static discordLoginUrl: string =
    "";

  public static getDiscordLoginLink(): string {
    if (window.location.href.includes("onrender")) {
      this.discordLoginUrl = "";
    } else if (window.location.href.includes("replit.dev")) {
      this.discordLoginUrl =
        "";
    } else if (window.location.href.includes("replit.app")) {
      this.discordLoginUrl =
        "";
    }

    return this.discordLoginUrl;
  }

  public static getBaseUrl(): any {
    if (window.location.href.includes("onrender")) {
      this.baseUrl = "h";
    } else if (window.location.href.includes("replit.dev")) {
      this.baseUrl =
        "";
    } else if (window.location.href.includes("replit.app")) {
      this.baseUrl =
        "";
    }

    return {
      cryptoUrl: this.baseUrl + "/crypto",
      baseUrl: this.baseUrl,
      discordUrl: this.baseUrl + "/discord-server",
    };
  }
}

const myVariable = "Hello from baseurl";

// baseurl.js
export const treat = {
  hello: "Hello from baseurl",
  ok: BaseUrl,
};

I build the file with tsc and is located in the dist directory

    <script type="module">
      import * as baseurlModule from "./dist/webpage/constants/baseurl.js";
      console.log("here is r: ", baseurlModule.treat);
    </script>

I want to use it here for example or even another typescript file, then compile it, but it would not work at all, no matter if I change the tsconfig, use exports instead of module.exports, and I know this is client side code. However, I have no idea the reasoning for it reading it as node.js file. I am able to only use one file at a time in HTML, but could not interact with each other

Another example

import { treat } from "../constants/baseurl";

import fetchfromclient from "./fetchfromclient";
window.onload = async () => {
  const { cryptoUrl, baseUrl, discordUrl }: IUrl =
    treat.ok.getBaseUrl() as IUrl;

//...

I have tried to use different type of javascript, whether it is type of module, export or import, nothing seems to work on using them interchangeably with each other.

Centralized Unsubscribe Function

PLEASE HELP!

Hi I am a fresh graduate newbie programmer and my boss give me a webpage project. The requirement is to create a 3rd party webpage that automate the unsubscribe process to our company’s 20 different website (technically, they have the same layout).

Now, I have a front-end and a data logs. But I don’t know how to redirect the email from the 3rd party form that I made to our main 20 unsubscribe websites.

The issue is I only have an access to the 20 unsubscribe form of our website but not in the back-end. I also don’t have an API-endpoint to begin with.

Is there any alternative way to build a centralized unsubscribe webpage? Is it possible to use token, if yes, how?

Since unsubscribing to 20 website over and over will took a lot of time. We want to build a webpage that automate the process by just answering one form and will automatically unsubscribe to the 20 website.

React + Tailwind, overlapping images in a marquee

I am trying to make an infinite scrolling animation, AKA marquee. I have 12 WEBP images, a React component and Tailwind animation. Also, I used Flex to align them. Here is the code.

Marquee component

import React from 'react';

interface MarqueeProps extends React.PropsWithChildren {
    className?: string;
}

export default function Marquee(p: MarqueeProps) {
    const props: MarqueeProps = { className: '', ...p };
    return <div className="flex flex-row">
        <div className={`${props.className} animate-marquee1`}>{props.children}</div>
        <div className={`${props.className} animate-marquee2`}>{props.children}</div>
    </div>;
}

animate-marqueeX

extend: {
    animation: {
        marquee1: 'marquee1 20s linear infinite',
        marquee2: 'marquee2 20s linear infinite'
    },
    keyframes: {
        marquee1: {
            '0%': {
                transform: 'translateX(0%)'
            },
            '100%': {
                transform: 'translateX(-100%)'
            }
        },
        marquee2: {
            '0%': {
                transform: 'translateX(100%)'
            },
            '100%': {
                transform: 'translateX(0%)'
            }
        }
    }
}

Invoking code

<Marquee className="flex scale-75 justify-center">
    {slideshow.map((src) => <img alt="" src={src} />)}
</Marquee>

context slideshow is a string[] containing paths to the images.
Here is a demo video: YouTube

You can look at the full code on GitHub: repo

Collapse sections with multiple levels

I’m working on a site that needs to expand several sections.

It’s not working correctly:

  1. Section 3.2 is not visible when you open section 3.
  2. When section 3 and 3.1 are both open, and you want to close section 3, the text of section 3.1 is still there.

I think the problem is in the Javascript.

Javascript

<script>
var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var content = this.nextElementSibling;
    if (content.style.display === "block") {
      content.style.display = "none";
    } else {
      content.style.display = "block";
    }
  });
}
</script>

<script>
var coll = document.getElementsByClassName("collapsible2");
var i;

for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("active");
    var content = this.nextElementSibling;
    if (content.style.display === "block") {
      content.style.display = "none";
    } else {
      content.style.display = "block";
    }
  });
}
</script>

CSS

<style>

body {
  background-color: #000000;
  margin:0;
  padding:0;
  -webkit-tap-highlight-color: transparent;
}

.collapsible {
  background-color: #303030;
  color: white;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-family: Arial;
  font-size: 15px;
  text-align: justify;
  margin-bottom: 1px;
}

.collapsible:focus {
  background-color: #555;
}

.collapsible2 {
  display: none;
  overflow: hidden;
  background-color: #303030;
  color: white;
  cursor: pointer;
  padding: 18px;
  padding-left: 40px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-family: Arial;
  font-size: 15px;
  text-align: justify;
  margin-bottom: 1px;
}

.collapsible2:focus {
  background-color: #555;
}



.content {
  padding: 0 3px;
  display: none;
  overflow: hidden;
  color: white;
  background-color: #000000;
  font-family: Arial;
  font-size: 15px;
  text-align: justify;
}


  
</style>

HTML

<button type="button" class="collapsible">&#127822; Section 1</button>

<div class="content"><p>Text here <a href="https://www.test.nl/" class="urltext">link text</a></p></div>

<button type="button" class="collapsible">&#127822; Section 2</button>

<div class="content"><p>Text here</p></div>

<button type="button" class="collapsible">&#127822; Section 3</button>

<button type="button" class="collapsible2">&#127822; Section 3.1</button>

<div class="content"><p>Text here</p></div>

<button type="button" class="collapsible2">&#127822; Section 3.2</button>

<div class="content"><p>Text here</p></div>

How to stop express from matching more than one route?

I have a router file that imports routes this way and gets required in index.js by require('./router.js')(app)

const index = require('./backend/pages/index')
const somepage = require('./backend/pages/somepage')

module.exports = function (app) {
    app.use('/', index)
    app.use('/:somepage/:page(page/\d+)?', somepage)
}

Matching for routes doesn’t stop after the first one is matched which I want to avoid, a similar problem to this one, but the solution wasn’t provided there

Here’s a route file for more info

const express = require('express'),
    router = express.Router()

router.get('/', async (req, res) => {
    console.log(`test ${Math.random()}`)
})

module.exports = router

I tried rearranging the router/routes in various ways but this doesn’t seem to help, I also tried changing app.use to app.get` but then the second route doesn’t get picked up