how can I repliacate the text typing effect from here? If you scroll down you will see how for example “Build for video” animates. I wonder which library is that or how to get that effect with css or javascript
Category: javascript
Category Added in a WPeMatico Campaign
Items in localStorage appear briefly but disappear after redirect
I’m working on a React app that’s currently deployed on Azure App service. I’ve got a log in system that worked in my dev environment but now is having issues saving user display data upon successful login.
Basically, I’m making a standard POST req to log in. It looks like this:
fetch('api...', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({email, password}),
credentials: 'include'
})
.then(res => return res.json())
.then(...)
In that second .then(...) block after I’ve received data back from the server, I have this logic:
if (!data || !data.success) {
// set error message and return
} else {
// Save the user display data so things like the Menubar can access it easily
localStorage.setItem('displayName', data.displayName);
localStorage.setItem('avatarRef', data.avatarRef);
localStorage.setItem('username', data.username);
// (A debug console.log() of the data received from server here)
// Redirecting to account page after 100ms here
setTimeout(() => {
window.location.href = '/account';
}, 100);
}
When I access the deployed website from my browser and log in, my authentication (cookies, etc.) are working, but these displayName etc. fields are briefly appearing in my localStorage before I get redirected from /account/login to /account.
By the way, when I console log the display name, etc., I do see the correct values in Devtools’ console. So I am indeed receiving the data, the browser just isn’t setting it correctly. I’ve tried this on both Chrome and Edge.
Theories for why the data isn’t persisting:
- Maybe I’m redirecting so fast that the localStorage hasn’t fully set in yet?
- Is the data disappearing as a consequence of using
window.location.hrefinstead of a redirect status code or some other redirection method?
If anyone has any general pointers as to where the issue might be here, I might be able to figure it out. Thanks!
Stripe payment method can’t seem be working
I’m encountering issues with Stripe payment processing in a client-server application. On the frontend, I’ve built a checkout form using @stripe/react-stripe-js and send payment data to the backend. However, there seems to be an issue with the amount sent from the client to the server. On the backend, I’ve set up Express.js routes to handle payments and explored Stripe’s payment intents logic. Despite ensuring proper Stripe API configuration, I’ve faced 500 Internal Server Errors during payment handling on the server. Additionally, I’ve noticed import errors related to the Stripe package in the client application.
[plugin:vite:import-analysis] Failed to resolve import "@stripe/react-stripe-js" from "srccomponentsCheckoutForm.jsx". Does the file exist?
C:/Users/Khaled/Desktop/pizza-si/client/src/components/CheckoutForm.jsx:1:52
9 | import { jsxDEV as _jsxDEV } from "react/jsx-dev-runtime";
10 | var _s = $RefreshSig$();
11 | import { CardElement, useStripe, useElements } from "@stripe/react-stripe-js";
| ^
12 | import PropTypes from "prop-types";
13 | import { useDispatch } from "react-redux";
server.js:
const express = require("express");
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
const app = express();
app.use(express.json());
app.use(express.static("public"));
app.use("/", (req, res) => {
res.send("Server is running!");
});
app.get("/success", (req, res) => {
res.sendFile(__dirname + "/public/success.html");
});
app.get("/cancel", (req, res) => {
res.sendFile(__dirname + "/public/cancel.html");
});
app.post("/payment", async (req, res) => {
try {
const paymentIntent = await stripe.paymentIntents.create({
amount: req.body.amount,
currency: "usd",
});
console.log("Payment intent created:", paymentIntent.id);
res.status(200).send({ clientSecret: paymentIntent.client_secret });
} catch (error) {
console.error("Payment failed:", error);
res.status(500).send({ error: "Payment failed" });
}
});
app.listen(3001, () => {
console.log("Server is running on port 3001");
});
checkoutForm.jsx:
import { CardElement, useStripe, useElements } from "@stripe/react-stripe-js";
import PropTypes from "prop-types";
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router-dom";
import {
startCheckout,
completeCheckout,
cancelCheckout,
} from "../redux/user/userSlice";
export default function CheckoutForm({ items, totalPrice }) {
const dispatch = useDispatch();
const navigate = useNavigate();
const stripe = useStripe(); // Add useStripe hook
const elements = useElements();
const handleSubmit = async (e) => {
e.preventDefault();
dispatch(startCheckout());
// Create a payment method using the CardElement
const { error, paymentMethod } = await stripe.createPaymentMethod({
type: "card",
card: elements.getElement(CardElement),
});
if (!error) {
// Send the payment method to your backend to create a payment intent
const response = await fetch("/create-payment-intent", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
payment_method_id: paymentMethod.id,
amount: totalPrice * 100, // Convert to cents
currency: "usd",
}),
});
const { clientSecret, error: paymentError } = await response.json();
if (clientSecret) {
const { paymentIntent, error: confirmError } =
await stripe.confirmCardPayment(clientSecret, {
payment_method: paymentMethod.id,
});
if (!confirmError) {
// If payment is successful, dispatch action to complete checkout and save payment details
dispatch(completeCheckout({ items, totalPrice }));
navigate("/success");
} else {
dispatch(cancelCheckout());
navigate("/cancel");
}
// Log the paymentIntent or handle it in some way
console.log(paymentIntent);
} else {
console.error(paymentError); // Log or handle payment errors
}
}
};
return (
<form onSubmit={handleSubmit}>
{/* ... */}
<CardElement />
{/* ... */}
</form>
);
}
CheckoutForm.propTypes = {
totalPrice: PropTypes.number,
items: PropTypes.array,
};
package.json for server:
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1",
"start": "node server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@stripe/react-stripe-js": "^2.3.2",
"@stripe/stripe-js": "^2.1.11",
"express": "^4.18.2",
"stripe": "^14.4.0"
}
}
package.json for client:
{
"name": "client",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"dependencies": {
"@emotion/styled": "^11.11.0",
"@mui/icons-material": "^5.14.8",
"@reduxjs/toolkit": "^1.9.5",
"@stripe/stripe-js": "^1.29.0",
"firebase": "^10.4.0",
"framer-motion": "^10.16.4",
"i18next": "^23.5.1",
"i18next-browser-languagedetector": "^7.1.0",
"i18next-http-backend": "^2.2.2",
"prop-types": "^15.8.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-firebase-hooks": "^5.1.1",
"react-i18next": "^13.2.2",
"react-icons": "^4.11.0",
"react-redux": "^8.1.2",
"react-router-dom": "^6.15.0",
"react-stripe-js": "^1.1.5",
"redux-persist": "^6.0.0",
"stripe": "^14.5.0"
},
"devDependencies": {
"@types/react": "^18.2.15",
"@types/react-dom": "^18.2.7",
"@vitejs/plugin-react-swc": "^3.3.2",
"eslint": "^8.45.0",
"eslint-plugin-react": "^7.32.2",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.3",
"vite": "^4.4.5"
}
}
How to change the text in a input from a Extension in Firefox?
I’m creating an extension to Firefox. The idea is while I’m writing in an editable element like a TextArea inside of different pages, after selecting a part of the text, change it based on the option selected in a context menu. Similar to the Grammarly extension.
I’m able to select the different options, get the text, and apply the option that I want, but I am not able or I can not find the option to substitute the text with the new text.
This is an example of my code that is currently working:
browser.contextMenus.onClicked.addListener((info, event, tab) => {
const optionSeletect = info.menuItemId;
const option = optionSeleted(optionSeletect); // Gets the option selected in the contextMenu.
const arrayText = getSelectedTextAsArray(info); // Extract the text selected
const newText = applyoption(arrayText,option); // Return the new text desired as a string.
});
It would be great if someone could help me. Thanks a lot!
Why is a transaction in my Firebase Cloud function not able to retrieve data which exists and thus, failing?
In my 2nd generation cloud function i have the following code:
export const roomEnter = functions.https.onCall(async (request: any) => {
// initial validation to verify user authentication and valid request data passes first
...
const roomRef = admin.database().ref(`rooms/${request.data.roomId}`);
const roomSnapshot = await roomRef.once("value");
const testDataExists = {
exists: roomSnapshot.exists(),
data: roomSnapshot.val()
};
functions.logger.log("[room enter] CHECK ROOM EXISTS:", JSON.stringify(testDataExists));
// In the logs, the data that exists DOES print to the console successfully
const transactionRef = admin.database().ref(`rooms/${request.data.roomId}`);
const transactionResult = await transactionRef.transaction((currentData) => {
functions.logger.log("[room enter] Transaction current data:", JSON.stringify(currentData));
// In the logs, `currentData` prints as `null`, why?
// As a result, the transaction never gets beyond this condition and fails i assume after it has exhausted all internal retries
if (currentData !== null) {
if (currentData.memberTotal) {
currentData.memberTotal += 1;
} else {
currentData.memberTotal = 1;
}
return currentData;
} else {
functions.logger.log("[room enter] Transaction needs to retry, room current data is null", {
roomId: request.data.roomId
});
return; // Returning undefined should cause Firebase to retry the transaction
}
});
if (transactionResult.committed) {
// never able to reach this point
} else {
functions.logger.log("[room enter] transaction to increment member total failed");
throw new functions.https.HttpsError("internal", "transaction to increment member total failed", {
customData: {
roomId: request.data.roomId
}
});
}
...
});
The test query i do immediately prior to the transaction is only there as a test to confirm the data exists.
And as noted in the code comments above, the transaction fails despite the reference path to existing data having been confirmed to exist.
Other than attempting to log errors everywhere possible, i am not sure how to troubleshoot this issue.
Other cloud functions i have which do not use transactions are able to read and write to the database without issue.
The only additional info i have aside from the logs, is that client side the error is reported to the client as a 500 internal server error along with the response which does include the error response containing the message transaction to increment member total failed.
With respect to my database security rules, as a test, in-order to rule this out as the cause i have set ".write": true for rooms and rooms/$roomId
So, why is currentData null inside the transaction?
What else can i do to troubleshoot?
PUT Request Blocked by CORS Policy [closed]
I have an API hosted in AWS ECS Cluster.
Here is the API:
import express from 'express'
import cors from 'cors'
import http from 'http'
const setupExpress = () => new Promise((resolve) => {
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true });
app.use(cors());
app.get('/health' , (req, res) => {
res.send('OK');
});
app.put('/user' , (req, res) => {
console.log('putting user...');
});
resolve(app);
});
const launchServer = (app) => new Promise((resolve, reject) => {
const server = http.createServer(app);
server.listen(5020);
server.on('listening', () => {
resolve();
})
server.on('error', (err) => {
console.log('Error starting server:', err.message);
reject(err);
});
});
setupExpress()
.then(launchServer);
(Please note that I’ve simplified the layout but for this instance the requests don’t reach the server so I don’t think it matters that much)
This configuration works. I am able to call GET '/health' to the URL of the Load Balancer connected to the service from a local React app.
But when I try to call POST /user from the same React app I get the following error:
Access to XMLHttpRequest at 'https://.../user/create' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Here is an example of how I make the API request in the app:
import axios from 'axios'
...
...
<button onClick={async() => {
await axios.post(import.meta.env.VITE_API_URL + '/user', {});
}}> Api Test </button>
...
...
In other places I use this singleton:
import axios , {AxiosInstance} from "axios";
class AxiosInstanceSingleton {
static instance = new AxiosInstanceSingleton();
static _userId = '';
ENTITY_MAPPING = {
'api': 'VITE_API_URL',
}
set userId(userId: string) {
AxiosInstanceSingleton._userId = userId;
}
_checkUserId = () => {
if(AxiosInstanceSingleton._userId === '') {
throw new Error('User ID is not set');
}
}
getAxiosInstance = (type: 'api') : AxiosInstance => {
this._checkUserId();
const baseURL = import.meta.env[this.ENTITY_MAPPING[type]]; // This can be localhost and can be my hosted URL
const instance = axios.create({
baseURL,
headers: {
"Content-Type": "application/json",
"X-User-ID": AxiosInstanceSingleton._userId,
},
})
return instance;
}
get api() {
return this.getAxiosInstance('api');
}
}
export default AxiosInstanceSingleton.instance;
(note that when a user log-in the singleton gets inited with his/hers ID)
In both ways I get the exact same error.
At the beginning I though maybe the X-User-ID header is the issue, making the POST request a complex request and then something in the pre-flight gets stuck but even the call without the header gives me issues so it can’t be that.
Mind that when I change the /user call to be GET for instance it works…
Appreciate all the help I can get!
function returns Promise { Undefined } on node JS [duplicate]
My NodeJS function keeps returning ‘Promise { Undefined }’
code:
const fs = require('fs')
async function readAccount(account){
fs.readFile('./Database/'+account+'/'+account+'.txt', 'utf8', function (err,data) {
if (err) {
console.error(err)
}
return data
})
}
console.log(readAccount('bingoteve'))
I tried asking chatGPT for help but its answers were outdated.
chromehtml2pdf renders too soon. Have page load event wait for asynchronous fetch() requests to resovle?
My webpage is rendered to PDF with chromehtml2pdf, which will execute the render when the page loads (I assume on the load event?). This page has react elements that are loaded asynchronously, after the load event. I want chromehtml2pdf to wait for all of these API calls to resolve.
chromehtml2pdf doesn’t seem to have much in the way of timing control. (I have moved away from tools such as wkhtmltopdf as the rendering engine is absolutely ancient and does not support the page content)
My next thought is modify the page so load doesn’t fire until all relevant fetch() calls have resolved. How do I go about this?
What is a good pattern for implementing rust-wasm constructors that will allow for javascript destructuring?
I’m using rust-wasm, wasm-bindgen, to create a javascript wrapper for a rust library.
I have a rust constructor currently defined like
#[wasm_bindgen(js_class = Dater)]
impl DaterWrapper {
#[wasm_bindgen(constructor)]
pub fn new(
dts: Option<String>,
code: Option<String>,
raw: Option<Vec<u8>>,
qb64b: Option<Vec<u8>>,
qb64: Option<String>,
qb2: Option<Vec<u8>>,
) -> Result<DaterWrapper> {
let dater = Dater::new(
dts.as_deref(),
code.as_deref(),
raw.as_deref(),
qb64b.as_deref(),
qb64.as_deref(),
qb2.as_deref(),
)
.as_js()?;
Ok(DaterWrapper(dater))
It generates a js type constructor:
constructor(dts?: string, code?: string, raw?: Uint8Array, qb64b?: Uint8Array, qb64?: string, qb2?: Uint8Array);
Which doesn’t allow for javascript destructuring. I’d like to used javascript destructuring to support named parameters in construction like new Dater({dts: now_datetime}).
Ignoring for the moment the poor design choice of allowing a constructor that can be constructed with different combinations of all optional parameters, is there any way to support destructuring (or a pattern) that makes this easy to do via wasm-bindgen? It seems like a common enough pattern that I’d rather not write js code to wrap the wrapper if there’s an easier way to do it from Rust or ideally some kind of macro.
How do I get gapi loading in react?
I have been trying to create a basic event using the google calendar API, firebase, and react but I keep getting the error that gapi is not loading. This is my code:
import * as React from "react";
import { Link } from 'react-router-dom';
import ApiCalendar from 'react-google-calendar-api';
import { apiCalendar } from "../../firebase/calendar";
import { useState } from "react";
import { gapi } from 'gapi-script';
import { confirmPasswordReset } from "firebase/auth";
export const LandingPageButtons = () => {
const [loading, setLoading] = useState(false);
const testCalendarApi = async () => {
try {
console.log("Clicked");
await apiCalendar.createEventFromNow({
time: 50,
summary: 'summary',
description: 'description'
});
console.log("Event created successfully!");
} catch (error) {
console.error("Error creating event:", error);
}
};
// Define the gapiLoaded function
const gapiLoaded = () => {
console.log("Gapi loaded from script tag");
console.log("token", gapi.auth.getToken());
};
// Attach the gapiLoaded function to the onload property of the script element
React.useEffect(() => {
const script = document.createElement("script");
script.src = "https://apis.google.com/js/api.js";
script.onload = gapiLoaded;
document.body.appendChild(script);
v
// Cleanup: remove the script when the component unmounts
return () => {
document.body.removeChild(script);
};
}, []); // The empty dependency array ensures that this effect runs only once
return (
<div className='bg-gradient-to-r from-blue-400 via-blue-300 to-blue-200 h-screen w-screen flex justify-center'>
<div className='w-4/5 sm:w-4/6 md:w-1/2 mx-auto'>
{/* Rest of your component */}
<div className='text-center h-30 mt-5 '>
<button
disabled={loading}
onClick={testCalendarApi}
className='bg-blue-900 text-white border-none rounded-lg cursor-pointer text-base w-4/5 h-16 sm:w-4/5 sm:h-14 md:text-lg md:w-6/12 transform transition-transform hover:scale-95 active:scale-100 hover:shadow-none shadow-lg'
>
Test Calendar API
</button>
</div>
</div>
</div>
);
};
I tried following react-google-calendar-api documentation (https://www.npmjs.com/package/react-google-calendar-api) to make a button that creates an event upon being hit, and right now my console shows that the event is being clicked + created, but because gapi is not loading no event is actually being made. Does anyone know what the problem may be? Thanks in advance!
Why is my Aleart Message not appearing after the user login wasn’t correct? Django, html, css
This is the Script in my signIn.html
{% if messg %}
<script>
aleart("{{messg}}");
</script>
{% endif %}
This is my Django View
def postsign(request):
email = request.POST.get("email")
passw = request.POST.get("pass")
try:
user = auth.sign_in_with_email_and_password(email,passw)
except:
message="Invalid credentials - try again"
return render(request, "signIn.html", {"messg":message})
print(user)
return render(request, "welcome.html", {"e":email})
def signIn(request):
return render(request, "signIn.html")
I was expecting an Aleart message on my screen that the Login was not correct.
Script code runs 3 times written in html using " [closed]
This was what I wrote:
<div
class="panel-selection"
onclick="alert("this isnt real")"
>
Pannel-Content
</div>
Magic. After clicked it, I got 3 replies in my browser.
[empty]
quotthis isnt real
this isnt real
Could anyone tell me what was going on with this in syntax logic if it is not a bug in my browser ? Thanks.
My browser uses Google Chrome 119.0.6045.160, 64-bit Build in Windows 10; language is zh-TW
What I want to receive:
I wonder some syntax logics in my question mentioned working in browser, the time when it reads the html.
I want why the js regard the syntax like that, which function was invoked in which forms and these linked problems.
In short, I want Escape symbols used in peers in html. If this form editing an onclick=”” function is feasible, please tell me how to edit it for a correct return.
regex check for global group validation (js)
hi i need to check the validity of all groups and the mixed possibility of creating a world.
for example:
asd
a s d
4 s d
444ssddd
aaaaa444ssss dddd
must all match.
while:
aesd
zxaxvd
anything that have not that pattern
i’ve try with something like this:
(a*|4*|4* *|a* *)(s*|s* *)(d*|d* *)
but this always return true, while should match the entire pattern group:
const regex = '(a*|4*|4* *|a* *)(s*|s* *)(d*|d* *)';
const re = new RegExp(regex, "gi");
const deleteMessage = re.test(text);
If there a conditional statement or formula to Prevent the unchecking of a checkbox after it has been checked by a user?
Trying to write a clock in/clock out sheet to better track time. I’m going to share the sheet with my employees. I have it where the time stamp is locked after a checkbox is checked so no one can tamper with their time. But I want an employee to not be able to uncheck the box after they have checked it through their shared document and recorded their time. Wanting this incase they leave early then try to get paid for more time than they worked. I’ve found a script but it doesn’t seem to be working at all, let alone the way I want it to.
For someone that a sheet is shared with to check a checkbox and then not be able to uncheck that checkbox
Javascript to Enter Password Comes back blank
I’m working on a little project that uses Javascript to login to a local server GUI page for display on a department wallboard/TV. I’m attempting to automate this process using a Chrome bookmark with javascript embedded in the Bookmark URL.
If I login to the site manually while running Wireshark I can see the following on the first POST method that appears and I’m successfully authenticated. See the bottom of screenshot:

The Username portion is already prefilled in since the Username box is a dropdown box and the default user is the one we want… So for the Javascript, I should only need to input the password and then submit the form.
But, when I run the Bookmark containing the following Code below, it acts as though the textbox is empty… I know I’ve seen similar things on certain sites. Where your login info gets auto-filled. But you need to manually click into the password field and enter a character and then delete it before it recognizes you entered any text. Same thing appears to happen here.
let passwordBox = document.querySelector("input[type='password']");
passwordBox.value = "myPassword";
console.log(passwordBox.value);
document.getElementById('loginButton').click();
console.log("Button clicked");
Here’s what Wireshark shows when using the Javascript above:

I even did an attempt where I removed the button click from the js, and then after the password was entered, I clicked into the textbox, added a space, and backspaced it, and the Hide/Show password button magically appeared, and clicking the Login button was successful.
Is there anything I can do to fix this?
Thanks in Advance,
Matt