How long is base64 url stored in local storage valid?

const scene = game.scene.getScene('default');
const canvas = scene.game.canvas;

// set size of the screenshot
const cropWidth = 350;
const cropHeight = 400;

// save the whole canvas as screenshot
const screenshotCanvas = document.createElement('canvas');
screenshotCanvas.width = canvas.width;
screenshotCanvas.height = canvas.height;

const context = screenshotCanvas.getContext('2d');
context.drawImage(canvas, 0, 0);

// crop center cropWidth x cropHeight area
const cropCanvas = document.createElement('canvas');
cropCanvas.width = cropWidth;
cropCanvas.height = cropHeight;

const cropContext = cropCanvas.getContext('2d');

// center cooridante
const sx = Math.round((canvas.width - cropWidth) / 2);
const sy = Math.round((canvas.height - cropHeight) / 2) - 50;
const sWidth = cropWidth;
const sHeight = cropHeight;

cropContext.drawImage(
  screenshotCanvas,
  sx,
  sy,
  sWidth,
  sHeight,
  0,
  0,
  cropWidth,
  cropHeight,
);

// Base64 convert
const base64 = cropCanvas.toDataURL('image/png');

// convert base64 to HTMLImageElement
const image = new Image();
image.src = base64;

// add as Phaser texture after being loaded
image.onload = () => {
  const index = localStorage.length + 1;
  scene.textures.addImage(`preset_${index}`, image);
  console.log(`Screenshot saved to cache as preset_${index}.`);

  // information will be stored in local storage
  const screenshotInfo = {
    index: index,
    data: base64,
    nameTag: nameTag,
    human: human,
    wing: wing,
    aura: aura,
    nickname: nickname,
  };

  // save in local storage
  localStorage.setItem(`preset_${index}`, JSON.stringify(screenshotInfo));

  // check saved data
  console.log('Saved image info:', screenshotInfo);
};

I use this code to save a screenshot of the phaser canvas in my local storage.

I could view the image by simply inserting the generated url into the browser link box.

But the problem is, I don’t know how long is this url valid.

Whether I clear the local storage or test it on a Incognito tab, the link was still valid.

Doesn’t this mean that the image information is being stored somewhere other than the local storage?

How can this link be expired?

Hostinger: Can’t get window.location.search

Hostinger builder just allow us to add a html code in a iframe section.

so, I added my code and I need to get window location search.

<script>
    async function getpostID(){
        const urlParams = new URLSearchParams(window.location.search);
        console.log(urlParams);
        const postId = urlParams.get('id');
        console.log(postId);
        return postId;
        
    }
    // Example function to fetch blog post by ID
    async function fetchBlogPostById(postId) {
      }
    document.addEventListener('DOMContentLoaded', () =>  fetchBlogPostById( getpostID() ));

</script>

I tried to set the function getpostID() in the integration section of Hostinger
but the internal code of the Iframe can’t see it

Keen-slider: Change animation duration and easing type for swiping

In the Keen Slider documentation, defaultAnimation is supposed to set the animation for moveToIdx, next, and prev functions. However, it only affects next and prev, not moveToIdx. I can change the animation duration for button clicks but not for swiping. Here’s the reproduction of the issue: https://stackblitz.com/edit/nuxt-starter-wuvuih?file=app.vue.

If we take a look at the unminified keen-slider source code and go to line 436 -https://codepen.io/simulant144/pen/WNqJvqz, there was a duration set to 500ms by default. If we change it to n.options.duration and then go to the line 825 and change this duration to let’s say 5000ms it starts to work. Is there a built-in way to set the animation duration and easing type to something like cubic-bezier(0.25, 0.1, 0.25, 1 particularly for swiping without going deep into the source code and changing it manually?

const current = ref(0);
const [container, slider] = useKeenSlider({
  slides: {
    perView: 1,
    spacing: 15,
  },
  initial: current.value,
  slideChanged: (s) => {
    current.value = s.track.details.rel;
  },
  defaultAnimation: {
    duration: 1300, // works only for navigation buttons and when clicking on gallery thumbnails, but not when swiping
  },
});

Looking forward for a possible solution.

Keen-slider: Slides appear all at once without spacing on initial page load

I’m using a route transition and when I refresh the page, I can see how slides appear all at once without spacing, and after the page is fully loaded they fall into place and are displayed correctly. I suppose the slider may be initializing before all elements and styles are fully loaded and applied, leading to incorrect spacing and layout initially. I tried putting the logic in onMounted and using nextTick, but it freezes the carousel instead.

Reproduction of the issue:
https://stackblitz.com/edit/nuxt-starter-ubrvzh?file=app.vue

Steps to reproduce:

If you don’t use a route transition, select throttling profile like ‘Slow 4G’ in the ‘Network’ section of the browser and reload the page to see the issue.

How do i query items from mongodb 2 different fields and in inside nested object

I try to query the following:

app.get("/api/leagues/:leagueId/:fixtureDate", async function (req, res) {

  const result = await client.db("db").collection("matches").find({
    $and: [
        { "date": req.params.fixtureDate },
        { "league.id": req.params.leagueId }
    ]
}).toArray();
  res.send(result);
});

League object looks like this:

"league": {
    "id": 2,
    "name": "UEFA Champions League",
    "country": "World",
    "logo": "CL.png",
    "flag": null,
    "season": 2024,
    "round": "1st Qualifying Round"
  }

But it returns an empty array [] when it should return fixtures that match the query filter

I experimented around a little bit and found that the problem has something to do with league.id, The server does receive the parameters from the frontend fine so it’s not that nor a typo mistake.

Cookie-session only works within the route I apply the data to

I am working on a project in express. I need to get certain fields from a login route into a session on the backend, so I can call the data from different routes. The problem is that when I try to access the data in a different route from where I save it, it doesn’t work. I am using cookie-session.

Below I include the relevant code

App.js:

// app.js
const express = require('express');
const cors = require('cors');
const session = require('cookie-session');
require('dotenv').config();

const app = express();
const port = process.env.PORT || 5000;

// Import MongoDB client
const client = require('./dbClient');

app.use(session({
  name: 'session',
  keys: [process.env.SESSION_SECRET],
}));

Auth.js

// Login route
router.post('/login', async (req, res) => {
  const { usernameoremail, password } = req.body;

  try {
    const usersCollection = client.db('DB').collection('users');
    const user = await usersCollection.findOne({
      $or: [{ username: usernameoremail }, { email: usernameoremail }]
    });

    if (!user) {
      return res.status(401).json({ message: 'Invalid credentials' });
    }

    const isMatch = await bcrypt.compare(password, user.password);

    if (!isMatch) {
      return res.status(401).json({ message: 'Invalid credentials' });
    }

    const token = jwt.sign(
      { userId: user._id, username: user.username, email: user.email, role: user.role },
      process.env.JWT_SECRET,
      { expiresIn: '1h' }
    );

    // Store in cookie-session
    req.session.user = {
      username: user.username,
      email: user.email,
      role: user.role,
    };

It is the same for the register route.

ticketsystem.js

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

// Import MongoDB client
const client = require('../dbClient');

const ticketsCollection = client.db('DB').collection('tickets');

// get user tickets
router.get('/tickets', async (req, res) => {
    try {
        const user = req.session.user;
        
        const tickets = await ticketsCollection.find({ user: user.username }).toArray();

        res.json(tickets);
    } catch (error) {
        console.error('Error fetching tickets:', error);
        res.status(500).json({ error: 'Internal server error' });
    }
});

module.exports = router;

What I’ve tried

  • I tried multiple libraries such as express-session and cookie parser.
  • I tried multiple configurations for the middleware.
  • I made sure that it was above all routes in app.py.

If anyone would be so kind to help me with this, I would really appreciate it!

CSS: “popup” close button not functional with my website?

Thanks in advance.

Question:

  1. I am using this code on my website:
// Aug 22 2024 social proof popup
setInterval(function() {
  $(".custom-social-proof").stop().slideToggle('slow');
}, 15000);
$(".custom-close").click(function() {
  $(".custom-social-proof").stop().slideToggle('slow');
});
/* Aug 22 2024 Social proof popup */

@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,600');
.custom-social-proof {
  position: fixed;
  bottom: 20px;
  left: 20px;
  z-index: 9999999999999 !important;
  font-family: 'Open Sans', sans-serif;
  //display: none;  /* Uncoment This Line to Hide Initially*/
  .custom-notification {
    width: 320px;
    border: 0;
    text-align: left;
    z-index: 99999;
    box-sizing: border-box;
    font-weight: 400;
    border-radius: 6px;
    box-shadow: 2px 2px 10px 2px hsla(0, 4%, 4%, 0.2);
    background-color: #fff;
    position: relative;
    cursor: pointer;
    .custom-notification-container {
      display: flex !important;
      align-items: center;
      height: 100px;
      .custom-notification-image-wrapper {
        img {
          max-height: 75px;
          width: 90px;
          overflow: hidden;
          border-radius: 6px 0 0 6px;
          object-fit: contain;
        }
      }
      .custom-notification-content-wrapper {
        margin: 0;
        height: 100%;
        color: gray;
        padding-left: 20px;
        padding-right: 20px;
        border-radius: 0 6px 6px 0;
        flex: 1;
        display: flex !important;
        flex-direction: column;
        justify-content: center;
        .custom-notification-content {
          font-family: inherit !important;
          margin: 0 !important;
          padding: 0 !important;
          font-size: 14px;
          line-height: 16px;
          small {
            margin-top: 3px !important;
            display: block !important;
            font-size: 12px !important;
            opacity: .8;
          }
        }
      }
    }
    .custom-close {
      position: absolute;
      top: 8px;
      right: 8px;
      height: 12px;
      width: 12px;
      cursor: pointer;
      transition: .2s ease-in-out;
      transform: rotate(45deg);
      opacity: 0;
      &::before {
        content: "";
        display: block;
        width: 100%;
        height: 2px;
        background-color: gray;
        position: absolute;
        left: 0;
        top: 5px;
      }
      &::after {
        content: "";
        display: block;
        height: 100%;
        width: 2px;
        background-color: gray;
        position: absolute;
        left: 5px;
        top: 0;
      }
    }
    &:hover {
      .custom-close {
        opacity: 1;
      }
    }
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<section class="custom-social-proof">
  <div class="custom-notification">
    <div class="custom-notification-container">
      <div class="custom-notification-image-wrapper">
        <img src="/images/sproofavatar.jpg">
      </div>
      <div class="custom-notification-content-wrapper">
        <p class="custom-notification-content">
          Anonymous Users<br>Took <b> The Nutritional Cell Organ Quiz</b>
          <small>Within The Past 4 Hours</small> <small><strong><a href="/questions/cell-organ-quiz.html" style="color:green;">Maybe you should also?</a></strong></small>
        </p>
      </div>

    </div>
    <div class="custom-close"></div>
  </div>
</section>
  1. The close button does NOT function at all on my website when I install the code there.
  2. Does anyone know what in the code above would conflict with my website to cause the close button not to function? I can click on it but it won’t close the popup as it does on the code above.

My website is here in shortened URL https://shorturl.at/SSnqN

  1. I tried to install the code as it is on my site
  2. It’s supposed to be allowed to let the user close the popup by clicking on the top right X close button.

2 Different websites with the same name? [closed]

I made a website hosted by godaddy, however today I discovered a strange bug. The purchased domain on godaddy is websitename.com, however, if you go to www.websitename.com it brings up an older version and the API doesnt work. Why does adding the www. change which page it goes to? Also if they are seperate, I never bought that?

ChatGPT told me to redirect websitename.com to www.websitename.com, which I did and Im waiting for it to update. Is that really the issue?

TypeError: options.getTextImputValue is not a function

I am trying to create a simple Discord Bot command, where I can create an embed. The problem seems to be in one line, where I want to get description of the embed from a modal. My problem lies somewhere in the line 38, tho I don’t know what is exactly wrong. Here’s my code:

const {SlashCommandBuilder, EmbedBuilder, ModalBuilder, TextInputBuilder, TextInputStyle, ActionRowBuilder} = require('discord.js');


module.exports = { 
data: new SlashCommandBuilder()
    .setName('embed-create')
    .setDescription('everything with embeds')
    .addStringOption(option => option.setName('title').setDescription('set the title for the embed').setRequired(true))
    .addStringOption(option => option.setName('color').setDescription('set color for your embed').setMaxLength(6).setRequired(true))
    .addStringOption(option => option.setName('thumbnail').setDescription('set thumbnail for your embed').setRequired(false))
    .addStringOption(option => option.setName('image').setDescription('set image for your embed').setRequired(false))
    .addChannelOption(option => option.setName('channel').setDescription('which channel should it be send to').setRequired(false)),


async execute(interaction) {
    const modal = new ModalBuilder()
            .setCustomId('creating')
            .setTitle('Nowy Embed')

        const desc = new TextInputBuilder()
            .setCustomId('a')
            .setLabel("Write Description here")
            .setStyle(TextInputStyle.Paragraph)
            .setPlaceholder("ex. sth went to school")

        const secondActionRow = new ActionRowBuilder().addComponents(desc)
        
        modal.addComponents(secondActionRow);
        
        await interaction.showModal(modal);

        await interaction.awaitModalSubmit({ time: 60_000 })
            .then(interaction => 
               interaction.reply({content: "Let's see", ephemeral: true}))
        
        const {options} = interaction;
            const title = options.getString('title');
            const description = options.getTextImputValue('a');
            const color = options.getString('color');
            const thumbnail = options.getString('thumbnail');
            const image = options.getString('image');
            const {channel} = options.get('channel');
            
            if (image){
               if (!image.startsWith('https')) { 
               await interaction.followUp({content:"Your image cannot be used! Use a link starting with http.", ephemeral: true})
                return}
            
            };
            
            if (thumbnail){
               if (!thumbnail.startsWith('https')) {
               await interaction.followUp ({content:"Your thumbnail cannot be used! Use a link starting with http.", ephemeral: true})
               return}
            };
            
            const embed = new EmbedBuilder()
             .setTitle(title)
             .setDescription(description)
             .setColor(`#${color}`)
             .setThumbnail(thumbnail)
             .setImage(image)

        await interaction.followUp ({content:"Your embed has been send below", ephemeral:(true)});
        await channel.send({ embeds: })

 }
}

Also, the cmd warns me with this error:

TypeError: options.getTextImputValue is not a function
    at Object.execute (botcommandsutilitycreate.js:46:41)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Client.<anonymous> (botindex.js:42:3)

As I worked on it for a while, I tried seeking about this problem and changed the code in various ways. I tried adding to te line

const description = options.getTextImputValue('a');

the options.fields.getTextImputValue but with no effect. Cmd even sent me, that it doesn’t recognize it as a command. I haven’t seen anyone encounter the same problem, so I need to ask about it myself.

I am currently working on vscode, node.js v20.16.0 and Discord.js v14.15.3.

Cannot pass variables from outer scope to `addInitScript` in Playwright

I am trying to create a generic login utility function in playwright. It would look something like:

const login = async (page, user) => {
  await page.addInitScript(() => {
    window.localStorage.setItem('user', JSON.stringify(user));
  })
}

Then in any given test, I can log in with a specific user:

test("Test login user 1", async ({ page }) => {
  await login(page, exampleUser1)
  // assert stuff
})

test("Test login user 2", async ({ page }) => {
  await login(page, exampleUser1)
  // assert other stuff
})

The problem here is that addInitScripts seems to not be able to take any arguments from outside its callback. I get an error that user is not defined. Apparently the code that’s inside that callback is ran “as is”, as if it were being stringified and then evaluated within the page.

How can I create a generic utility function that applies a variable localStorage value on page load?

Caching Scripts imported by web workers?

Web workers can import scripts in the worker thread like this with importScripts (This example if from HighlightJS ):

onmessage = (event) => {
  importScripts('https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.10.0/highlight.min.js');
  const result = self.hljs.highlightAuto(event.data);
  postMessage(result.value);
};

If we want the script to be cached by the browser so that the worker does not initiate another network request is it simply a matter of placing the script tag in the header like this?

<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.10.0/highlight.min.js" integrity="sha512-6yoqbrcLAHDWAdQmiRlHG4+m0g/CT/V9AGyxabG8j7Jk8j3r3K6due7oqpiRMZqcYe9WM2gPcaNNxnl2ux+3tA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>

NextJS rewrite does not delete URL search param

I have an email auth and after user clicks the button to access my website I have to check whether they have tokens or not. When they are redirected to my page from Gmail they have verification_token=** searchParam and if they have already been authorized I have to delete it.

As NextJS docs say, I have to use NextResponse.rewrite function in middleware.ts with deleting that token but next just shows the page with the same search param. I use app router and Next 14

As I mentioned, I used rewrite function with deleting the searchParam with url.searchParams.delete('verification_token'); but it does not help. The param is still there.

I have tried multiple variants with nextResponse.redirect etc. but nothing helped.

Get binance assets using OAuth

I’m working on integrating Binance APIs into my mobile app, and I’ve successfully registered my OAuth app on the Binance OAuth portal. After the user signs in to my app, I’m able to obtain an access_token.

Now, I would like to retrieve the user’s assets, similar to how it’s done with Coinbase, where you can get the user’s assets and balances through the /v2/accounts endpoint.

My question is:

Is there a specific Binance API endpoint that allows me to retrieve the user’s assets and balances using the access_token obtained from OAuth?

If so, what is the correct process for doing this? Are there any specific scopes or permissions I need to request during the OAuth process?

Failing to extract an ID from an InnerHTML string segment stored in sessionStorage

The teo lines in the script section of my html page are these …

 var mySession = sessionStorage.getItem("catProfile");
 var myValue = mySession.getElementByID("catAge");

The mySession variable correctly returns the stored string which is the inner html of a larger element. The stored/retrieved variable looks like this…as you can see the ID catAge, exists, but the myValue variable is erroring out, not finding it, am I using the wrong technique? Any help appreciated.

      <img class="profile-photo" src="/images/cats/vimes.webp">
      <img class="care-icon" src="" <="">
      <p class="name">Sir Vimes</p>
      <p id="catAge" class="age">3 aƱos</p>

      <div class="details">
        <img class="photo-one" src="/images/cats/vimes_one.webp" loading="lazy">
        <img class="photo-two" src="/images/cats/vimes_two.webp" loading="lazy">
        <img class="photo-three" src="/images/cats/vimes_three.webp" loading="lazy">

        <p class="title">Beautiful, Playful and Affectionate Calico</p>
        <p class="story">
          This cat was found by the side of the street in a cardboard box,
          she was hungry and wet from being in the rain. She has a wonderful
          personalty, is friendly and loving.
        </p>
        <p class="health">No health issues</p>
        <p class="gender">Female</p>
        <p class="fee">$50.000 COP</p>
        <p class="cuddle-factor">3</p>
        <p class="activity-factor">7</p>
        <p class="cat-friendly">yes</p>
        <p class="dog-friendly">no</p>
      </div>
    

    

Upload middleware not executing upon being called by route

I’m making a fullstack mern application that features a form that should allow users to upload images. I’ve confirmed that the files are properly appended to the body of the request, but when the request reaches the endpoint its supposed to use the upload middleware to store the images in an s3 bucket. After debugging I realized that none of the code in the middleware is running. I checked the file path on the require statement so I’m not sure why the code isn’t running.

const auth = require('../middleware/auth.js');
const upload = require('../middleware/upload.js');

// POST Route for event creation
router.post('/event', auth, upload.array('eventPhotos', 5), async (req, res) => {
  try {
      // Extract image URLs from the uploaded files
      const eventPhotos = req.files.map(file => file.location);

      const newEvent = {
          title: req.body.title,
          description: req.body.description,
          street: req.body.street,
          city: req.body.city,
          state: req.body.state,
          postalCode: req.body.postalCode,
          timezone: req.body.timezone,
          startDate_startTime: req.body.startDate_startTime,
          endDate_endTime: req.body.endDate_endTime,
          participants: req.body.participants,
          eventPhotos: eventPhotos,
          tickets: req.body.tickets, // Parse tickets from string to array if necessary
          attendantId: generateAttendantNumber(),
          eventId: uuidv4(),
          location: req.body.location
      };

      user.events.push(newEvent);
      await user.save();

      res.json({ 
          msg: 'Event created successfully', 
          eventUrl: `http://localhost:3000/payment/${newEvent.eventId}`, 
          attendantCode: newEvent.attendantId 
      });
  } catch (err) {
      console.error(err.message);
      res.status(500).send('Server Error');
  }
});

//upload.js
const multer = require('multer');
const multerS3 = require('multer-s3');
const aws = require('aws-sdk');
const path = require('path');

// Configure AWS SDK
aws.config.update({
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
    region: process.env.AWS_REGION,
});

const s3 = new aws.S3();


// Configure Multer-S3
const upload = multer({ 
    storage: multerS3({
        s3: s3,
        bucket: process.env.S3_BUCKET_NAME,
        acl: 'public-read', // Allows public read access to the uploaded files
        key: function ( file, cb) {
            cb(null, `${Date.now().toString()}-${file.originalname}`);
        },
    }),
    limits: { fileSize: 10 * 1024 * 1024 }, // Limit file size to 10MB
    fileFilter: function ( file, cb) {
        const ext = path.extname(file.originalname);
        if (ext !== '.jpg' && ext !== '.jpeg' && ext !== '.png') {
            return cb(new Error('Only images are allowed'), false);
        }
        cb(null, true);
    },
});

module.exports = upload;

Like I said I’m not sure its the file path and the client seems to pass the information on without issue. The specific error I got was:

Cannot read properties of undefined (reading 'map')

I figured out that this was because req.files was undefined, after that I realized that my middleware wasn’t running at all.

Here’s the server.js file as well

// server.js

const express = require('express');
const connectDB = require('./config/db');
const cors = require('cors');
const cookieParser = require('cookie-parser');
const path = require('path');

// Routes
const usersRouter = require('./routes/users.js');
const publicRoutes = require('./routes/publicRoutes');
const protectedRoutes = require('./routes/protectedRoutes');

const app = express();

// Connect to MongoDB
connectDB();

// Middleware
app.use(cors()); // Enable CORS for all routes
app.use(express.json()); // Parse JSON bodies
app.use(cookieParser()); // Cookie monster

app.use(express.static(path.join(__dirname, 'client/build')));

// Define routes
app.use('/api/users', usersRouter);
app.use('/api/public', publicRoutes); // Public routes
app.use('/api/protected', protectedRoutes); 
app.use('/uploads', express.static('uploads'));


app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname + '/client/build/index.html'));
});

// Define port
const PORT = process.env.PORT || 5000;

app.get('/', (req, res) => {
  res.send('Hello, welcome to the API server!');
});

app.get('/success', (req, res) => {
  res.send('Purchase success');
});

app.get('/cancel', (req, res) => {
  res.send('>:( You canceled');
});

// Start server
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});