How to use querySelectorAll instead of other methods in targeting multiple elements?

I need to target all the img elements inside .lazy-load-wrapper class and add multiple attribute to it . And I need to use querySelectorAll but I encountered an error Uncaught TypeError: elmnt.setAttribute is not a function. I think I need to loop the element inside querySelectorAll because it is a static Nodelist, but how can I do that?.

Here are the codes:

function theLazyLoader () {
  const eleAttributes = {
    loading: 'lazy',
    class: 'lazy-load-spinner',
  };
  function setMultipleAttributes(elmnt, attributesToSet) {
    Object.keys(eleAttributes).forEach(i => {
      elmnt.setAttribute(i, eleAttributes[i]);
    });
  }
  const img = document.querySelectorAll('.lazy-load-wrapper img');
  setMultipleAttributes(img, eleAttributes); 
}
theLazyLoader();
img {
  width: 400px;
  height: 300px;
  display: block;
  margin: 10px auto;
  border: 0;
}

.lazy-load-spinner {
  background: url("https://cdn.pixabay.com/animation/2023/10/10/13/27/13-27-45-28_512.gif") center center/100px 100px no-repeat #F1F1FA;
}
<div class="lazy-load-wrapper">
  <img src="https://ik.imagekit.io/demo/img/image1.jpeg?tr=w-400,h-300" />
  <img src="https://ik.imagekit.io/demo/img/image2.jpeg?tr=w-400,h-300" />
  <img src="https://ik.imagekit.io/demo/img/image3.jpg?tr=w-400,h-300" />
  <img src="https://ik.imagekit.io/demo/img/image4.jpeg?tr=w-400,h-300" />
  <img src="https://ik.imagekit.io/demo/img/image5.jpeg?tr=w-400,h-300" />
  <img src="https://ik.imagekit.io/demo/img/image6.jpeg?tr=w-400,h-300" />
  <img src="https://ik.imagekit.io/demo/img/image7.jpeg?tr=w-400,h-300" />
  <img src="https://ik.imagekit.io/demo/img/image8.jpeg?tr=w-400,h-300" />
  <img src="https://ik.imagekit.io/demo/img/image9.jpeg?tr=w-400,h-300" />
  <img src="https://ik.imagekit.io/demo/img/image10.jpeg?tr=w-400,h-300" />
</div>

JS “Unbound breakpoint” when trying to debug files using swaggerAPI

I am encountering an issue with debugging JavaScript and TypeScript files in a project utilizing an Express server and Swagger API (Swagger).

The problem arises when attempting to set breakpoints in the controller files. These breakpoints are not being set, and I receive the error: “Unbound breakpoint”. However, I am able to debug initialization files, such as index.ts and expressServer.js, without any issues.

Steps to reproduce:

  1. Add breakpoint in index.ts

  2. Add breakpoint in expressServer.js

  3. Add breakpoint in some of the controller files.

  4. Launch the debugger (The server is stopped)

  5. The debugger breaks in index.ts file

  6. Upon continue(F5) breaks in expressServer.js

  7. Take a look at the breakpoint in some of the controller files and verify it is grayed out with message “Unbound breakpoint”

  8. Request the server via Postman

  9. Unable to send a request (loading infinitely) since the server is not started

Note: I am testing it on virtual machine where it has NodeJS v20.17.0 and TypeScript 5.7.2


I suspect that the problem lies with the Swagger API configuration. The configuration file openapi.yaml used by Swagger appears to be distributing the requests to the controllers and their endpoints, making these files inaccessible to the debugger. If this assumption is incorrect, I would appreciate any clarification or guidance on resolving this issue.

Thank you for your assistance.

Server initialization files:

expressServer.js

// const { Middleware } = require('swagger-express-middleware')
const http = require('http')
const https = require('https')
const fs = require('fs')
const path = require('path')
const swaggerUI = require('swagger-ui-express')
const jsYaml = require('js-yaml')
const express = require('express')
const cors = require('cors')
const cookieParser = require('cookie-parser')
const bodyParser = require('body-parser')
const OpenApiValidator = require('express-openapi-validator')
const logger = require('./logger')
const config = require('./config')

const { getBasePath } = require('./utils/swaggerUtils')
const { updateAPISpecification } = require('./utils/fixes')

const { entrypoint } = require('./utils/entrypoint')

const cleanPath = (path) => path.replace(////,'/')

class ExpressServer {
  constructor(port, openApiYaml) {
    this.port = port;
    this.app = express();
    this.openApiPath = openApiYaml;
    try {
    
      this.schema = jsYaml.safeLoad(fs.readFileSync(openApiYaml))
      
      updateAPISpecification(this.schema, openApiYaml)

    } catch (e) {
      logger.error('failed to start Express Server', e.message)
    }

    this.setupMiddleware()
  
  }

  setupMiddleware() {

    const basePath = getBasePath().replace(//$/,'')

    // this.setupAllowedMedia();
    this.app.use(cors())
    // this.app.use(bodyParser.json({ limit: '14MB' }))
    this.app.use(express.json())
    this.app.use(express.text())
    this.app.use(express.urlencoded({ extended: false }))
    this.app.use(cookieParser())
    
    //Simple test to see that the server is up and responding
    this.app.get('/hello', (req, res) => res.send(`Hello World. path: ${this.openApiPath}`))
    
    const openapi=config.OPENAPI || '/openapi'

    //Send the openapi document *AS GENERATED BY THE GENERATOR*
    this.app.get(cleanPath(`${basePath}${openapi}`), (req, res) => res.sendFile((path.join(__dirname, 'api', 'openapi.yaml'))))

    //View the openapi document in a visual interface. Should be able to test from this page
    this.app.use(cleanPath(`${basePath}/api-docs`), swaggerUI.serve, swaggerUI.setup(this.schema))

    this.app.get('/login-redirect', (req, res) => {
      res.status(200)
      res.json(req.query)
    })

    this.app.get('/oauth2-redirect.html', (req, res) => {
      res.status(200)
      res.json(req.query)
    })
    
    this.app.get(`${openapi}`, function(req, res) {
      res.redirect(cleanPath(`${basePath}/${openapi}`))
    })

    this.app.get('/api-docs', function(req, res) {
      res.redirect(cleanPath(`${basePath}/api-docs`))
    })

    this.app.use(cleanPath(`${basePath}/entrypoint`), entrypoint)

    this.app.get('/', function(req, res) {
      res.redirect(cleanPath(`${basePath}/entrypoint`))
    })

    this.app.get(cleanPath(`${basePath}/`), function(req, res) {
      res.redirect(cleanPath(`${basePath}/entrypoint`))
    })

    const apiTimeout = 5 * 1000
    if(false) this.app.use((req, res, next) => {
        // Set the timeout for all responses
        res.setTimeout(apiTimeout, () => {
            let err = new Error('Service Unavailable')
            err.status = 503
            next(err)
        })
    })

  }

  launch() {
    
    try {
      
      this.app.use( OpenApiValidator.middleware({
            apiSpec: this.openApiPath,
            operationHandlers: path.join(__dirname, 'built'),
            validateRequests: true, // (default)
            validateResponses: true, // false by default
            unknownFormats: ['base64']
        }))
        
      // this.app.use(validator)

      logger.info(`validator installed`)
  
      this.app.use((err, req, res, next) => {
        // format errors
        res.status(err.status || 500).json({
          message: err.message || err,
          errors: err.errors || '',
        })
      })

      let server; 

      const fullchainPath = '/certificates/fullchain.pem';
      const privkeyPath = '/certificates/privkey.pem';

      if (fs.existsSync(fullchainPath) && fs.existsSync(privkeyPath)) {
        logger.info('Running with SSL');
        const sslCert = {
          cert: fs.readFileSync('/certificates/fullchain.pem'),
          key: fs.readFileSync('/certificates/privkey.pem')
        };
        server = https.createServer(sslCert, this.app)
      } else {
        logger.info('Running without SSL');
        server = http.createServer(this.app)
      }

      server.listen(this.port)

      logger.info(`Listening on port ${this.port}`)
       
    } catch(e) {
        logger.error(`launch error: ` + e)
    }

  }


  async close() {
    if (this.server !== undefined) {
      await this.server.close();
      logger.info(`Server on port ${this.port} shut down`)
    }
  }
}

module.exports = ExpressServer;

index.ts

import config from './config';
import logger from './logger';
import ExpressServer from './expressServer';

import Service from './services/Service';
import NotificationHandler from './services/NotificationHandler';

import plugins from './plugins/plugins';

Service.setDB(plugins.db);
Service.setNotifier(NotificationHandler);

NotificationHandler.setDB(plugins.db);
NotificationHandler.setQueue(plugins.queue);

class ServerLauncher {
  private expressServer: ExpressServer | undefined;

  public async launchServer(): Promise<void> {
    try {
      this.expressServer = new ExpressServer(config.URL_PORT, config.OPENAPI_YAML);
      await this.expressServer.launch();
      logger.info('Express server running');
    } catch (error) {
      logger.error(error);
      await this.close();
    }
  }

  private async close(): Promise<void> {
    if (this.expressServer) {
      await this.expressServer.close();
    }
  }
}

const serverLauncher = new ServerLauncher();

serverLauncher.launchServer().catch((error) => logger.error(error));

This is the configuration i use:

launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Launch Program",
      "skipFiles": ["<node_internals>/**"],
      "program": "${workspaceFolder}/built/index.js",
      "preLaunchTask": "tsc: build - tsconfig.json",
      "outFiles": ["${workspaceFolder}/built/**/*.js"],
      "port": 9229
    }
  ]
}

tsconfig.json

{
  "compilerOptions": {
    "target": "ES6", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    "module": "commonjs", /* Specify what module code is generated. */
    "rootDir": "./",                                  /* Specify the root folder within your source files. */
    "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
    "outDir": "./built", /* Specify an output folder for all emitted files. */
    "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
    "strict": true, /* Enable all strict type-checking options. */
    "skipLibCheck": true /* Skip type checking all .d.ts files. */
  },
  "include": ["/**/*.ts"],
  "exclude": ["node_modules", "**/*.spec.ts"]
}

How can I create a dynamic FetchXML query to filter specific columns when using Power Pages List?

This is the FetchXML that I am working with at the moment, but i would like the value to be dynamic based on what the user inputs.

`<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false">
  <entity name="cr554_sanctions_lists">
    <attribute name="cr554_names" />
    <filter type="or">
      <condition attribute="cr554_names" operator="like" value="%QASIM%" />
    </filter>
  </entity>
</fetch>`

This FetchXML needs to be inputted in a list in Power Pages

I have also tried liquid but couldn’t figure out how to do it.

When fetched, date is shows as one day behind. The DB has correct data stored [closed]

I have a node.js and MySQL project. the user inputs the date from a dropdown and submits the form. In the backend, i see proper date but when i fetch it, its 1 day behind. Ive read that it might be a UTC problem but i dont understand how to fix it
I have some custom js for this to avoid userinput

html:

            <label for="dob" class="form-label">Date of Birth</label>
            <input type="date" class="form-control" id="dob" name="dob" required value="{{formData.dob}}">
            <div class="invalid-feedback">Please enter your date of birth.</div>
          </div>

and the js:

  //set limit
  const dateInput = document.getElementById("dob");
  const maxDate = new Date().setFullYear(new Date().getFullYear() - 18);
  dateInput.setAttribute("max", new Date(maxDate).toISOString().split('T')[0]);

  dateInput.addEventListener("keydown", function(event) {
    event.preventDefault(); // Prevent typing
  });
  dateInput.addEventListener("input", function(event) {
    event.preventDefault(); // Prevent input
  });

Vue JS 3 + Firebase: How to call Cloud Run Function (2nd gen Firebase Function) which requires authentication

  1. My app is created using Vue JS 3 and firebase is installed as a
    dependency.

  2. I created a firebase app to handle the backend. To
    handle the rest api calls from the Vue JS app I am creating a
    firebase function.

  3. The function has following dependencies in package.json:

    “dependencies”: {
    “cors”: “^2.8.5”,
    “express”: “^4.21.2”,
    “firebase-admin”: “^12.6.0”,
    “firebase-functions”: “^6.0.1”
    },

  4. The index.js in the functions folder looks like below:

const {onRequest} = require("firebase-functions/v2/https");
const {getAuth} = require("firebase-admin/auth");

const express = require("express");
const app = express();

// Add middleware to authenticate requests
app.use(async (req, res, next) => {
  const authHeader = req.headers.authorization || "";
  const token = authHeader.split("Bearer ")[1];

  if (!token) {
    return res.status(401).json({error: "Unauthorized"});
  }

  try {
    const decodedToken = await getAuth().verifyIdToken(token);
    req.user = decodedToken;
    next();
  } catch (error) {
    console.error("Error verifying token:", error);
    res.status(403).json({error: "Forbidden"});
  }
});

app.get("/hello", (req, res) => {
  res.json({message: "Hello, world!"});
});

// Expose Express API as a single Cloud Function:
exports.api = onRequest(app);

Here the function’s name is: “api”.
Now this setup works fine in local while testing.

After deploying the function the function url looks something like this: “https://REGION-MY-APP-NAME.cloudfunctions.net/api”.

Now, from the Vue JS 3 app, using axios I am trying to hit the above end point and using a firebase method to generate the token which looks like below:

    const userCredential = await signInWithEmailAndPassword(auth, emailId.value, password.value);
const token = await userCredential.user.getIdToken(); // Get the token

But this gives CORS error in the browser, (Note: I tried adding cors policy in my function code to allow all origin but it did not help)

On the other hand, in the Cloud run Function log, it says:

“The request was not authenticated. Either allow unauthenticated
invocations or set the proper Authorization header. Read more at
https://cloud.google.com/run/docs/securing/authenticating Additional
troubleshooting documentation can be found at:
https://cloud.google.com/run/docs/troubleshooting#unauthorized-client”

After getting this error, I removed below code from my index.js as well and tried. but gave the same error:

// Add middleware to authenticate requests
app.use(async (req, res, next) => {
  const authHeader = req.headers.authorization || "";
  const token = authHeader.split("Bearer ")[1];

  if (!token) {
    return res.status(401).json({error: "Unauthorized"});
  }

  try {
    const decodedToken = await getAuth().verifyIdToken(token);
    req.user = decodedToken;
    next();
  } catch (error) {
    console.error("Error verifying token:", error);
    res.status(403).json({error: "Forbidden"});
  }
});

I know, there is an option “Allow unauthenticated invocations” under the function settings. But due to some policy restriction I am unable to do so.

And I also know that there is some problem in either my token generation method in my Vue JS 3 app. I found a link to generate the token in node js (https://cloud.google.com/docs/authentication/get-id-token#node.js)

My problem is I only have a Vue JS 3 app in front-end and I want to use this 2nd gen function as my backend with express js to do backend related tasks like storing and retrieving data from Cloud FireStore and related things… But stuck at this authentication error. Need to help resolving this 403 auth error.

If any other information is needed. Please let me know, I will provide.

How to detect and block a webp image that has jpg extension?

some webp images when saved have .jpg extension but I want to explicitly disallow webp type files because it is still too heavy in size for my storage. This is my working code in javascript that detects and disallows non jpg/png file extensions, but webp images with extensions of jpg obviously will still pass through

$.each(previousFiles, function(index, file) {

const fileExtension = file.name.split('.').pop().toLowerCase();

    if (!allowedExtensions.includes(fileExtension)) {

        alert('Only JPG and PNG files are allowed.');

            return;

    }

};

once passed through ajax, I also process it in PHP and this is my code to only allow jpeg, jpg, png files

$filePath = $uploadPath . $newName;

$fileExtension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));

if (!in_array($fileExtension, ['jpeg', 'jpg', 'png'])) {

    return $this->response->setJSON([

    'success' => false,

    'message' => 'Only JPG and PNG files are allowed.'

    ]);

}

but the webp images still gets through most likely because these codes only detect the extension. How can I detect if it is a webp and explicitly return a message that it is not allowed?

I have tried using this code

$.each(previousFiles, function(index, file) {

const fileExtension = file.name.split('.').pop().toLowerCase();

    if (!allowedExtensions.includes(fileExtension)) {

        alert('Only JPG and PNG files are allowed.');

            return;

    }

};

once passed through ajax, I also process it in PHP and this is my code to only allow jpeg, jpg, png files

$filePath = $uploadPath . $newName;

$fileExtension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));

if (!in_array($fileExtension, ['jpeg', 'jpg', 'png'])) {

    return $this->response->setJSON([

    'success' => false,

    'message' => 'Only JPG and PNG files are allowed.'

    ]);

}

still webp images with jpg extensions passes through. I am guessing I need more than a file extension detection code but I am at my wits end.

How do I embed a React build folder to an existing HTML website?

I have a chat widget built with React.
The button to open the widget looks like this:
widget

I ran npm run build, which produced the build folder.
The build folder looks like this:

build folder

I copied the build folder to a FastAPI server and changed the name of the main javascript and main css to this:

build folder in fast api

I serve the files with these FastAPI routes:
fast api routes

In the HTML where I want to embed the widget (the host website), I put a link tag and a script tag to pull the main js and css from the FastAPI server.

link tags in host html

I do npm run start on the host website and get this:

brain image not found

The brain PNG is not found. Looking in the network tab, I see this:

inspect network

It’s looking for the brain image at http://localhost:3001/static/media/brain.05079b7891cefa47d585.png

What’s the proper way of embedding a React build folder to an existing React website? I tried looking in the docs but no luck.

how to know if facebook share was successful?

i am following this documentation to implement faebook share using javascript sdk

https://developers.facebook.com/docs/sharing/reference/share-dialog/

here is the full code.

<body>


<script>
    window.fbAsyncInit = function() {
        FB.init({
            appId            : '${grailsApplication.config.facebookAppId}',
            xfbml            : true,
            version          : 'v21.0'
        });


    };
</script>
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js"></script>




<a href="#" onclick="myFacebookLogin()">Share me</a>





<script>
// Only works after `FB.init` is called
function myFacebookLogin() {

    $('#fooBar').hide();
    $('#noThanksSection').hide();
    $('#status').show();
    
    
    
    var lnk = $('input[name=referralLink]').val();
    


    FB.ui({
        method: 'share',
        href: lnk
        }, function(response){


            if(response  &&  !response.error_code){
                    $('#nextSection').show();
                    $('#noThanksSection').hide();
                    alert("Post was successful!");
                    $('#status').hide();
            }
            else{
                    alert('Error occured! Please try again!');
                $('#fooBar').show();
                $('#noThanksSection').show();
                $('#status').hide();

            }


        });



}
</script>

<body>

Clicking on the button will show the share popup window. After sharing the post, the javascript true block should execute in if(response && !response.error_code){ but the false block is executing. The response is empty.

How can we know if the facebook post was shared or the popup window was closed without sharing?

I appreciate any help! Thanks!

Issues playing audio in website on iOS devices

I’ve build a basic webpage with a countdown timer that plays 3 short sounds at different points through the countdown, once the countdown is complete, a stopwatch timer appears and waits for the user to press stop.

The .play() function doesn’t seem to work on my iPhone for both Chrome and Safari. None of the three sounds are audible at all.

It plays fine for desktops and there are no issues at all.

Is there a fix for this? The whole idea of the training tool is that it is supposed to work on mobiles so competitors can train their reaction times at home.

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css" rel="stylesheet">
<style>
    #processed-content {
        background-image: url('https://www.slslnc.org.au/wp-content/uploads/timerbackground.jpg');
        background-position: center;
        background-size: cover;
        min-height: 96vh;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding: 16px;
        text-align: center;
    }

    #processed-content h1,
    #processed-content p {
        color: black;
        text-shadow: 0 0 15px white;
        font-size: 2rem;
        margin:50px 0;
    }
    
    p#timerDisplay.instructions {
    font-size: 18px !important;
}

    #processed-content button {
        color: black;
        font-size: 2rem;
        margin:20px 0;
    }
    .start-button {
        background-color:#ffd520;
        border:2px solid black;
    }
    .stop-button {
        background-color:#ed1c2e;
        border:2px solid black;
    }
    .reset-button {
        background-color:#00cc36;
        border:2px solid black;
    }
    .save-button {
        background-color:#0066db;
        border:2px solid black;
    }
    
    .hidden {
        display: none;
    }
    
    @media screen and (max-width:768px) {
    p#timerDisplay.instructions {
    font-size: 18px !important;
    }
}
</style>

<div id="processed-content">
    <h1 class="text-2xl font-bold mb-4">Beach Flags Reaction Time Trainer</h1>
    <button id="startButton" class="bg-gold hover:bg-gray-200 text-black font-bold py-4 px-10 rounded mb-4 start-button">START</button>
    <p id="timerDisplay" class="text-lg mb-4 instructions">When you press START, you will have up to 15 seconds to get into position and be ready for the audio prompts...</p>
    <button id="stopButton" class="hidden bg-white hover:bg-gray-200 text-black font-bold py-4 px-10 rounded mb-4 stop-button">STOP</button>
    <button id="resetButton" class="hidden bg-white hover:bg-gray-200 text-black font-bold py-2 px-4 rounded reset-button">RESET</button>
    <button id="screenshotButton" class="hidden bg-white hover:bg-gray-200 text-black font-bold py-2 px-4 rounded mt-4 save-button">SAVE SCREENSHOT</button>
</div>

<audio id="readyAudio" src="https://www.slslnc.org.au/wp-content/uploads/competitorsready.mp3"></audio>
<audio id="headsDownAudio" src="https://www.slslnc.org.au/wp-content/uploads/headsdown.mp3"></audio>
<audio id="whistleAudio" src="https://www.slslnc.org.au/wp-content/uploads/whistle.mp3"></audio>

<script>
    const startButton = document.getElementById("startButton");
    const stopButton = document.getElementById("stopButton");
    const resetButton = document.getElementById("resetButton");
    const screenshotButton = document.getElementById("screenshotButton");
    const timerDisplay = document.getElementById("timerDisplay");

    const readyAudio = document.getElementById("readyAudio");
    const headsDownAudio = document.getElementById("headsDownAudio");
    const whistleAudio = document.getElementById("whistleAudio");

    let countdownTimeout, headsDownTimeout, whistleTimeout, stopwatchInterval;
    let startTime;

    startButton.addEventListener("click", function() {
        startButton.classList.add("hidden");
        timerDisplay.textContent = "Get ready...";

        const randomCountdown = Math.floor(Math.random() * 6) + 10;

        countdownTimeout = setTimeout(() => {
            readyAudio.play();
            
            const randomReadyTime = Math.floor(Math.random() * 2) + 3;

            headsDownTimeout = setTimeout(() => {
                headsDownAudio.play();
                
                const randomWhistleTime = Math.floor(Math.random() * 3) + 2;

                whistleTimeout = setTimeout(() => {
                    whistleAudio.play();
                    startStopwatch();
                }, randomWhistleTime * 1000);
            }, randomReadyTime * 1000);
        }, randomCountdown * 1000);
    });

    function startStopwatch() {
        startTime = Date.now();
        stopButton.classList.remove("hidden");
        
        stopwatchInterval = setInterval(() => {
            const elapsedTime = ((Date.now() - startTime) / 1000).toFixed(2);
            timerDisplay.textContent = `Time: ${elapsedTime} s`;
        }, 10);
    }

    stopButton.addEventListener("click", function() {
        clearInterval(stopwatchInterval);
        stopButton.classList.add("hidden");
        resetButton.classList.remove("hidden");
        screenshotButton.classList.remove("hidden");
    });

    resetButton.addEventListener("click", function() {
        clearTimeout(countdownTimeout);
        clearTimeout(headsDownTimeout);
        clearTimeout(whistleTimeout);
        timerDisplay.textContent = "Get ready...";
        resetButton.classList.add("hidden");
        screenshotButton.classList.add("hidden");
        startButton.classList.remove("hidden");
    });

    screenshotButton.addEventListener("click", function() {
        html2canvas(document.querySelector("#processed-content")).then(canvas => {
            const link = document.createElement('a');
            link.href = canvas.toDataURL();
            link.download = 'reaction_time.png';
            link.click();
        });
    });

    function loadHtml2Canvas() {
        const script = document.createElement("script");
        script.src = "https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js";
        document.body.appendChild(script);
    }

    loadHtml2Canvas();
</script>

Getting two notifications in foreground only

I am using Firebase Cloud Messaging (FCM) to send data-only messages in my React Native app. However, when a notification is received in the foreground, I am getting two notifications in the handler.

const getFCMToken = async () => {
  try {
    let fcmToken = await AsyncStorage.getItem('fcmToken');
    console.log('******** fcmToken 1', fcmToken);

    if (!fcmToken) {
      // Get the FCM token
      fcmToken = await messaging().getToken();
      await AsyncStorage.setItem('fcmToken', fcmToken);
    }
    let data = { fcm_token: fcmToken };
    console.log('yvguhbijn', data);
    let response = await HomeService.postFCMToken(data);
    if (response?.data?.success) {
      Toast.show('FCM set successfully');
    }
  } catch (error) {
    console.error('Error getting FCM token:', error);
  }
};

const displayBgContent = async (remoteMessage) => {
  const { data } = remoteMessage;

  // Generate a default title and body if not provided
  const title = data?.title;
  const body = data?.body;

  // Safely parse the actions field
  let actions = [];
  try {
    const parsedActions = JSON.parse(data?.actions || '[]'); // Parse or default to an empty array
    actions = parsedActions.map((action) => ({
      title: action.name.toUpperCase(), // Example: "BUY"
      pressAction: {
        id: action.name, // Example: "buy"
        launchActivity: 'default',
      },
    }));
  } catch (error) {
    console.error('Failed to parse actions:', error);
  }
  // Check if the image URL exists and is valid
  const image = data?.image && data.image.trim() !== '' ? data.image : null;

  // Display notification using notifee
  if (actions.length == 0) {
    await notifee.displayNotification({
      title,
      body,
      android: {
        channelId: 'default',
        smallIcon: 'notification_icon', // Ensure you have this icon in your project
        largeIcon: image || 'default_icon', // Fallback to a local image if no valid URL
        importance: AndroidImportance.HIGH,
        pressAction: {
          id: 'default',
        },
        badge: true,
        color: '#FF7900',
        onlyAlertOnce: true,
        style: image
          ? {
              type: AndroidStyle.BIGPICTURE, // Show a big picture style notification
              picture: image,
            }
          : undefined, // Skip style if no image
      },
      ios: {
        foregroundPresentationOptions: {
          badge: true,
          sound: true,
          banner: true,
          list: true,
        },
        categoryId: 'customCategory', // Match the category ID registered earlier
        sound: 'default', // Notification sound
        attachments: image
          ? [
              {
                url: image, // Attach image only if it exists
              },
            ]
          : [], // Empty array if no image
      },
      data, // Include the original payload for further handling
    });
  } else {
    await notifee.displayNotification({
      title,
      body,
      android: {
        channelId: 'default',
        smallIcon: 'notification_icon', // Ensure you have this icon in your project
        largeIcon: image || 'default_icon', // Fallback to a local image if no valid URL
        importance: AndroidImportance.HIGH,
        actions: actions, // Attach dynamic actions
        badge: true,
        color: '#FF7900',
        onlyAlertOnce: true,
        style: image
          ? {
              type: AndroidStyle.BIGPICTURE, // Show a big picture style notification
              picture: image,
            }
          : undefined, // Skip style if no image
      },
      ios: {
        foregroundPresentationOptions: {
          badge: true,
          sound: true,
          banner: true,
          list: true,
        },
        categoryId: 'customCategory', // Match the category ID registered earlier
        sound: 'default', // Notification sound
        attachments: image
          ? [
              {
                url: image, // Attach image only if it exists
              },
            ]
          : [], // Empty array if no image
      },
      data, // Include the original payload for further handling
    });
  }
};

const listenToInAppNotifications = async () => {
  const unsubscribe = messaging().onMessage(async (remoteMessage) => {
    await displayBgContent(remoteMessage);
    const { messageId } = remoteMessage;

    if (!messageId) {
      return;
    }

    // Cancel the notification after displaying it
    try {
      await notifee.cancelNotification(messageId);
      console.log(`Notification with ID ${messageId} canceled successfully`);
    } catch (error) {
      console.error(
        `Failed to cancel notification with ID ${messageId}:`,
        error,
      );
    }
  });

  return unsubscribe;
};

Getting two notifications in both android and ios.I am using firebase messaging and notifee for displaying the notifications.

WordPress interfering with javascript modal popup

My site is built on WordPress, but I also have many PHP based pages. My Wiki is built from my database. I am trying to show another page of my own site (entitycard.php) in a javascript popup iframe, when hovering over a link to show stats of in-game weapons/armors/items. It works great, but for some reason entitycard.php is giving me the WordPress “Sorry, no posts matched your criteria” issue.

See video below showing the problem on my site, but it working great on localhost. Here is also a screenshot of the issue on my site versus it working in localhost. I appreciate any insight.

Working in localhost versus issue in PROD:
enter image description here

enter image description here

Website where you can see the issue:
https://www.kisnardonline.com/wiki/players.php?name=Tomek
https://www.kisnardonline.com/wiki/entitycard.php?entityid=697711

entitycard.php is just a connection to database and then output. Nothing WordPress within it.
enter image description here




Code below for anyone who may want to beg, borrow, steal 🙂

CSS style:

    <style>
        /* The Modal (background) */
        .modal {
            display: none; /* Hidden by default */
            position: fixed; /* Stay in place */
            z-index: 1; /* Sit on top */
            left: 0;
            top: 0;
            overflow: auto; /* Enable scroll if needed */
            background-color: rgb(0,0,0); /* Fallback color */
            background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
        }

        /* Modal Content/Box */
        .modal-content {
        }
    </style>

onmouseover hover js/php and popup iframe:

...
echo "<td><a onmouseover="showPopup(this)" onmouseout="hidePopup(this)" href="entity.php?entityid=$entity_id">$name_with_quantityplusraritystarlevel</a></td>";
...
echo "<div id="myModal" class="modal">";
    echo "<div class="modal-content">";
        echo "<iframe onload="resizeIFrameToFitContent()" id="popupcontent" height="200px" width="150px"></iframe>";
    echo "</div>";
echo "</div>";

Javascript for popup hide/show:

<script>
    // START: Code for popup on entity link hover
    var modal = document.getElementById('myModal');
    // To show the modal popup when hovering over the Entity URL link
    showPopup = function(context) {
        let link = context.href;
        link = link.replace("entity.php", "entitycard.php");
        //link example is https://www.kisnardonline.com/wiki/entitycard.php?entityid=697711
        modal.style.display = "block";
        document.getElementById("popupcontent").src = link;
        resizeIFrameToFitContent();
    };

    // When the user moves mouse off of link, close the modal
    hidePopup = function(context) {
        modal.style.display = "none";
    }
    
    // To resize the popup iFrame
    function resizeIFrameToFitContent() {
        document.getElementById("popupcontent").width  = 0;
        document.getElementById("popupcontent").height  = 0;
        document.getElementById("popupcontent").width  = document.getElementById("popupcontent").contentWindow.document.documentElement.scrollWidth + 7;
        document.getElementById("popupcontent").height = document.getElementById("popupcontent").contentWindow.document.documentElement.scrollHeight;
    }
    // END: Code for popup on entity link hover
</script>

Azure issue unresponsive pings on port 8080

I created an app with a react front end and go back end. I was able to store the go backend in a docker container and then deploy it to azure and create a web app for it. The backend is working successfully when i make requests on postman. The issue I’m having is when i try connecting my frontend code through my github repo, it is saying that the container didn’t respond to pings on port 8080. I’ve been searching google and asking chatgpt for solutions for the past two days with no luck. I’ve made 100’s of different modifications to my package.json for a fix. Here is my current package.json scripts section:

"scripts": {
    "start": "serve -s build -l $PORT",
    "build": "react-scripts build",
    "test": "react-scripts test --passWithNoTests",
    "eject": "react-scripts eject"
  },

It’s working locally but just won’t work when i attempt to deploy at all. Any help would be greatly appreciated.

getting token from paypal javascript code to process payment

I’m trying to figure out how to use Paypal’s javascript SDK to allow a customer to go on paypal website (or by filling in the payment form) so that I can get the credentials needed to process a payment using their backend api, but their example doesn’t explain things well. This is the code I used so far:

<!DOCTYPE HTML>
<html>
<head>
<title>.</title>
<meta charset="utf-8">
</head>
<body>
<h1>Test</h1><div ID="paypal-button-container"></div>
<script src="https://sandbox.paypal.com/sdk/js?client-id=myid&intent=authorize&commit=false&components=buttons,marks,messages,applepay&currency=CAD"></script>
<script>
paypal.Buttons({
  style: {
layout: 'vertical',
color:  'blue',
shape:  'rect',
label:  'paypal'
  }
}).render('#paypal-button-container');
paypal.Buttons({
  async createOrder() {
    const response = await fetch("/my-server/create-paypal-order", {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
    },
    body: JSON.stringify({
        cart: [
        {
            sku: "YOUR_PRODUCT_STOCK_KEEPING_UNIT",
            quantity: "YOUR_PRODUCT_QUANTITY",
        },
        ],
    }),
    });

    const data = await response.json();

    return data.id;
},
async onApprove(data) {
    // Capture the funds from the transaction.
    const response = await fetch("/my-server/capture-paypal-order", {
      method: "POST",
      body: JSON.stringify({
    orderID: data.orderID
      })
    })

    const details = await response.json();

    // Show success message to buyer
    alert(`Transaction completed by ${details.payer.name.given_name}`);
}
}).render('#paypal-button-container');


</script>
</body>
</html>

What it does is it displays the same payment choices twice but one paypal button in gold color and one in blue colour.

I have also tried:

<!DOCTYPE HTML>
<html>
<head>
<title>.</title>
<meta charset="utf-8">
</head>
<body>
<h1>Test</h1><div ID="paypal-button-container"></div>
<script src="https://sandbox.paypal.com/sdk/js?client-id=myid&intent=authorize&commit=false&components=buttons,marks,messages,applepay&currency=CAD"></script>
<script>
paypal.Buttons({
  style: {
layout: 'vertical',
color:  'blue',
shape:  'rect',
label:  'paypal'
  },
  async createOrder() {
    const response = await fetch("/my-server/create-paypal-order", {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
    },
    body: JSON.stringify({
        cart: [
        {
            sku: "YOUR_PRODUCT_STOCK_KEEPING_UNIT",
            quantity: "YOUR_PRODUCT_QUANTITY",
        },
        ],
    }),
    });

    const data = await response.json();

    return data.id;
},
async onApprove(data) {
    // Capture the funds from the transaction.
    const response = await fetch("/my-server/capture-paypal-order", {
      method: "POST",
      body: JSON.stringify({
    orderID: data.orderID
      })
    })

    const details = await response.json();

    // Show success message to buyer
    alert(`Transaction completed by ${details.payer.name.given_name}`);
}
}).render('#paypal-button-container');


</script>
</body>
</html>

but no success there either.

I have used the correct client ID but for the code here I put in myid for easier readability.

What am I doing wrong?

How to use Online Database with Axios

if (!err.email && !err.password) {
    axios.post('http://localhost:8082/login', values) //
    .then((res) => {
        if (res.data === 'Invalid Email or Password') {
            alert('No Record Found');
        } else if (res.data.status === 'Login Success') {
            localStorage.setItem('userName', res.data.name);
            navigate('/GUI/dashboard');
        } else {
            alert('Some error: ' + res.data);
        }
    })
    .catch((err) => console.error(err));
}

In code snippet, I have used Axios. There currently I have used localhost and I want to make this online. So I want to use an online database instead of localhost MySQL databse with XAMPP server. There,

With what should I replace “http://localhost:8082/login” if I want to use CleverCloud MySQL database instead of localhost MySQL version?