Safari and Chrome in IOS does not listen to server sent events when the browser is in the background

I’m trying to redirect my Angular web application to a different URL that receives from server-sent events. This feature works well when the browser is in the foreground in IOS. However, when a user changes the browser to the background, the Angular application does not listen to any events.

This issue only happens in IOS. In Andriod, browsers receive server-sent events even when the browser is in the background.

service.ts

getServerSentEvent(merchantTransactionId: string, txnDate: string): Observable<any> {
    return new Observable<string>(obs => {
      const appType = 'guest-checkout';
      const url = environment.BASE_DATA_URL + '/api/event/server-sent/event/subscribe/' + appType + '/' + merchantTransactionId;
      const es = new EventSource(url);
      es.addEventListener('message', (event) => {
          // alert(event.data);
          obs.next(event.data);
      });
      return () => es.close();
    });
  }

I have added an alert box to test whether it appears on mobile or not. It does not appear when the browser is in the background. Also, I have tried onmessage instead of addEventListener and there was no change.

Component.ts

triggerSSEEvent(merchantTxnId, txnDateString): void {
    this.sseService.getServerSentEvent(merchantTxnId, txnDateString).subscribe(
      (data) => {
        const response = JSON.parse(data);
        this.responseURL = response.url;
        window.location.href = response.url;
      },
      (error) => {
        this.showError();
      }
    );
  }

Note: The user usually switches the browser in order to accept the push request from another app.

Variabel won’t keep values using Heroku

A very small example

let value = null;
const getValues = () => {
  fetch('/third-party-api')
    .then(res => res.json())
    .then(data => {
      value = data;
    })
}

getValues();

app.get("/values", async (req, res) => {
  res.json(value);
});

When it is getting deployed, it will work.
But after x-amount of time, the value will get back to being null.
I am paying for Heroku, so the server will never sleep, and this is why it doesn’t make sense to me why this happens.

Can I somehow prevent this, so the value won’t get back to being null?

req.send(new FormData(formElement)) in to call HttpServlet

I need to develop a Login Page with an HTML page, javascript and Java Servlet.

This is my problem. The params of the login form seem to be always empty debugging request servlet.
In Javascript I encounter this error on req.send(new FormData(…)) line.

(Part of) HTML File:

<div class="container" style="max-width: 30%; margin: 0;  position: absolute;  top: 50%;  left: 50%;  transform: translate(-50%, -50%); ">
    <h1>Login</h1>
    <h3>Accedi per effettuare i tuoi ordini</h3>
    <div id="errormessage" class="alert alert-warning" role="alert"></div>
    <form action="#">
        <fieldset>
    <div class="form-group">
        <label for="username">Username</label>
        <input required type="text" name="username" id="username" class="form-control">
    </div>
    <div class="form-group">
        <label for="pwd">Password</label>
        <input required type="password" class="form-control" name="pwd" id="pwd">
    </div>
    <input type="button" class="btn btn-primary" id="loginbutton" value="Accedi">
        </fieldset>
    </form>

utils.js

function makeCall(method, url, formElement, cback, reset = true) {
        var req = new XMLHttpRequest(); // visible by closure
        req.onreadystatechange = function() {
          cback(req)
        }; // closure
        req.open(method, url);
        if (formElement == null) {
          req.send();
        } else {
          req.send(new FormData(formElement));
        }
        if (formElement !== null && reset === true) {
          formElement.reset();
        }
      }

loginManagement.js

(function() { // avoid variables ending up in the global scope

  document.getElementById("loginbutton").addEventListener('click', (e) => {
    var form = e.target.closest("form");
    if (form.checkValidity()) {
      makeCall("POST", 'login', form,
        function(req) {
          if (req.readyState == XMLHttpRequest.DONE) {
            var message = req.responseText;
            switch (req.status) {
              case 200:
                sessionStorage.setItem('username', message);
                window.location.href = "home.html";
                break;
              case 400: // bad request
                document.getElementById("errormessage").textContent = message;
                break;
              case 401: // unauthorized
                  document.getElementById("errormessage").textContent = message;
                  break;
              case 500: // server error
                document.getElementById("errormessage").textContent = message;
                break;
            }
          }
        }
      );
    } else {
         form.reportValidity();
    }
  });

})();

Is there a free Map service API that I can use/customize and draw circles / polygones on it to track optical fiber design in a city?

My project is about tracking optical fiber componenents(cables,connectors…) of a city and show them in a Map.

So, i’m searching for a Map API to use in my application where I have a database containing many points identified by their longitudes and latitudes, I’m searching for a Map API where I can draw these points(fetched from the database) on the Map, and show their informations when click on a point.

Here’s an example (Click on the link below) from vetroFiberMap Site, I’m looking for map Api like it.

Note:
I tried Google Maps but most services are paid.

Thanks.

Image for what I’m looking for

Recording clicks and keystrokes to a csv

I’m attempting to make a Chrome extension that records the number of clicks, keystrokes, and time spent within a certain period of time on a given website (e.g., 45 clicks, 296 keystrokes, and 129 minutes spent on Facebook within one week). I’ve never coded before and the course I’m writing this code for did not cover Chrome extensions.

So far, I’ve figured out how to make a simple message appear in the console log when I click the webpage (code given below), but that’s about it. How would I export the number of clicks to a .csv?

manifest.json

    "name": "Social Media Consumption Tracker",
    "version": "1.0",
    "manifest_version": 2,
    "content_scripts": [
        {
            "matches": ["https://www.facebook.com/*",
            "http://www.facebook.com/*"],
            "js": ["content.js"]
        }
    ],
  "permissions": ["tabs"]
}

content.js

document.addEventListener("click", e=> {
    console.log("Hey there")
})

Thank you in advance for your help.

Image not rendering in my Admin application

I am creating a admin application where i want to display uploaded images of product stored in database. I have uploaded images as an object id in MongoDB. But the image container in admin app displays the number of images stored in database. But the images are not displayed. I tried using absolute URL too but that doesnot work either.

Here is my code to upload images:

{productPictures.length > 0
          ? productPictures.map((pic, index) => (
              <div key={index}>{pic.name}</div>
            ))
          : null}
        <input
          type="file"
          name="productPictures"
          onChange={handleProductPictures}
        />

Here is the code to display images:

<label className="key">Product Pictures</label>
            <div style={{ display: "flex" }}>
              {productDetails.productPictures.map((picture) => (
                <div className="productImgContainer">
                  <img src={generatePublicUrl(picture.img)} alt="" />
                </div>
              ))}
            </div>

Generate URL function looks like this:

const api ='http://localhost:2000/'
// const api = 'http://192.168.0.104:2000/'
const generatePublicUrl = (fileName) => {
    return `http://localhost:2000/src/uploads/products/${fileName}`;
}
export {
    api,
    generatePublicUrl
};

Function to save product in database:

const createProduct= (req, res) => {
  const { name, price, description, category, quantity, createdBy } = req.body;
  let productPictures = [];

  if (req.files.length > 0) {
    productPictures = req.files.map((file) => {
      return { img: file.location };
    });
  }

  const product = new Product({
    name: name,
    slug: slugify(name),
    price,
    quantity,
    description,
    productPictures,
    category,
    createdBy: req.user._id,
  });

  product.save((error, product) => {
    if (error) return res.status(400).json({ error });
    if (product) {
      res.status(201).json({ product, files: req.files });
    }
  });
        
}

The uploaded images in program looks like this:
Open image here

But the page displays blank area and filename shows undefined when inspected.
Open image here

how to config the webpack 5.x to remove the dist folder before build

Before the next build, I want to remove the previous build because if we do not remove the old build, some change that did not generate the output file may not be found as soon as possible. I am tried to do this work using this command in the package.json right now:

"dev": "rm -rf src/bundle && webpack --mode development --config build/webpack.dev.config.js",

but I feel this way may be a little dangerous with the rm -rf command, any better suggetion?

document.getElementById().style.backgroundImage works with server file directory but not local file directory

I wrote a website last year using raw html, css, and js, but I’ve been attempting to rebuild my code with react as a good exercise to learn the tool. I’ve noticed that my old code to reset my backgroundImage no longer works if I use a local image directory within the url(...) pointer, and only works with actual http:// urls. When the new code runs, the backgroundImage goes white if a local png is being used. I’ve been scratching my head for some time so I’d appreciate any help.

Old code:

function randombg(){
    var random= Math.floor(Math.random() * 2) + 1;
    var bigSize = ["url('background-images/1.png')",
                   "url('background-images/2.png')",
                   ...
    document.getElementById("random").style.backgroundImage=bigSize[random];
}

CSS:

#random {
    width: 100%;
    height: 100vh;
    background-image: url('assets/background-images/1.png');
    background-repeat: repeat; 
    position: absolute;
    z-index: -1;
}

New code is the same but uses a react function to run the js (handleClick(e) {…}).

get array contents from a list of objects and create a new one [duplicate]

How are you, I’ve been trying to find an answer for a while and without success.
I am trying to get the array of a series of objects and from here create a single list.
I think it’s easier to show it.
This is the json file to read:

  {
  "Mnix_Active": [
      {
      "area": "Citytes",
      "name": "Ridemk"
      },
      {
      "area": "City77",
      "name": "Delivery"
      }
  ],
  "Storm": [
      {
      "area": "City152",
      "name": "Rescue"
      },
      {
      "area": "City22",
      "name": "Resupply"
      }
  ],
  "Meganix": [
      {
      "area": "Park22",
      "name": "Ride"
      },
      {
      "area": "City25",
      "name": "Ride"
      }
  ]     
  
}

and get it like this::

    [
        {
        "area": "Citytes",
        "name": "Ridemk"
        },
        {
        "area": "City77",
        "name": "Delivery"
        },
        {
        "area": "City152",
        "name": "Rescue"
        },
        {
        "area": "City22",
        "name": "Resupply"
        },
        {
        "area": "Park22",
        "name": "Ride"
        },
        {
        "area": "City25",
        "name": "Ride"
        }     
    
    ]

How to use offset pagination with Prisma and SWR

I am trying to upgrade my pagination to use Prisma and SWR. I am currrently storing all posts from an api call in an array and using this to paginate. What I would like to do is use SWR and Prisma to pass take and skip dynamically.

Currently I have the following:

//index.js
import React, { useState, useEffect } from 'react';
import Posts from './components/Posts';
import Pagination from './components/Pagination';

const App = () => {
  const [posts, setPosts] = useState([]);
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [postsPerPage] = useState(10);

  useEffect(() => {
    const fetchPosts = async () => {
      setLoading(true);
      const res = await fetch`${process.env.NEXT_PUBLIC_SERVER_API}/posts/get take=15&skip=15`,
      setPosts(res.data);
      setLoading(false);
    };

    fetchPosts();
  }, []);

  // Get current posts
  const indexOfLastPost = currentPage * postsPerPage;
  const indexOfFirstPost = indexOfLastPost - postsPerPage;
  const currentPosts = posts.slice(indexOfFirstPost, indexOfLastPost);

  // Change page
  const paginate = pageNumber => setCurrentPage(pageNumber);

  return (
    <div className='container mt-5'>
      <h1 className='text-primary mb-3'>My Blog</h1>
      <Posts posts={currentPosts} loading={loading} />
      <Pagination
        postsPerPage={postsPerPage}
        totalPosts={posts.length}
        paginate={paginate}
      />
    </div>
  );
};

export default App;
//Pagination Component
import React from 'react';

const Pagination = ({ postsPerPage, totalPosts, paginate }) => {
  const pageNumbers = [];

  for (let i = 1; i <= Math.ceil(totalPosts / postsPerPage); i++) {
    pageNumbers.push(i);
  }

  return (
    <nav>
      <ul className='pagination'>
        {pageNumbers.map(number => (
          <li key={number} className='page-item'>
            <a onClick={() => paginate(number)} href='!#' className='page-link'>
              {number}
            </a>
          </li>
        ))}
      </ul>
    </nav>
  );
};

export default Pagination;

What I would like to do is use Prisma’s offset pagination, dynamically passing take and skip.

So using SWR like this:

  const { data: posts, error } = useSWR(
    `${process.env.NEXT_PUBLIC_SERVER_API}/posts/get?take=10&skip=10`,
    fetcher
  );

Here is my Prisma query:

const posts = await prisma.post.findMany({
      take: parseInt(take),
      skip: parseInt(skip),
      select: {
        id: true,
        title: true,
      },
      orderBy: {
        title: "asc",
      },
    });
res.json(posts)

How can I dynamically pass and track pagination using take and skip on the frontend?

how to avoid Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist

I am developing a google chrome plugin, when I open the plugin popup UI, shows an error like this in the devtool console:

Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

I just wonder what should I do to avoid this problem? someone said that the background.js send message to script.js, when the script.js is not ready will face this error, I checked my code and did not send any message in the background.js. this is what the error looks like in the devtool console.

enter image description here

why the google chrome show that the error came from HTML? is it possible to let the chrome tracing into which js file throw this error? from the error and tracing information, I have no idea where is going wrong and what should I do to fix it or avoid it.

A bug I am facing with JqueryUI draggable/droppable

I would appreciate if someone can help me out,

here’s my code :

`https://jsfiddle.net/m796a3ud/`

What I want to do is drag an image from these list of Images and be able to get a clone that’s draggable, and when I put it inside the box it counts how many images are inside, it works good for the most part but when I try to drag the cloned image in and out of the box a couple of times the clone gets cloned it self which is not what I want, I would really appreciate the help!

thanks.

Dynamically change preload script

Is there a way to set/change the preload option in webPreferences after BrowserWindow has been created?

What I would like to do is make a webcrawler that changes its preload script whenever the BrowserWindow redirects to a new URL.

The issue that I am trying to solve is that the webcrawler needs to collect different information on different sites.

The only 2 solutions I can think of are:

  1. make 1 massive preload script that covers every website or
  2. create a new BrowserWindow with a different preload script each time it redirects,

but neither seems resource efficient.

Is it possible to change or use different preload scripts without using multiple instances of the BrowserWindow?