How to pass and handle parameters Durable functions v4 javascript?

I’m very new with durable functions V4 in javascript but I cannot get this activity to run properly. I always get an error as apparently I’m not passing in the Instance ID correctly.

What am I doing wrong here? The tutorial page on the microsoft website was of no use.

Here is the code:

df.app.orchestration('reportOrchestrator', function* (context) {
   try {
       const instanceId = context.df.instanceId; // Get the current orchestration's instance ID
       context.log(`Orchestration instance ID: ${instanceId}`);

       const lsFile = { instanceID: instanceId }; // Pass instanceID in an object
       const token = yield context.df.callActivity('TokenManager', { instanceID: instanceId }); 

context.log(`Token retrieved: ${token}`);


return token;

  // const result = yield context.df.callActivity('PipelineQuery', { token });

  } catch (error) {
    return error.message;
    context.log(`Error in orchestration: ${error.message}`);
    throw error;
  }
});
df.app.activity('TokenManager', {
   handler: async (context) => {
        const log = context.log;

         const lsFile = context.getClient().instanceID; // Direct input passed from the orchestrator

if (!lsFile || !lsFile.instanceID) {
    //log("InstanceID is missing or undefined");
    throw new Error("InstanceID is missing or undefined,", context);
}

const instanceID = lsFile;
//log(`Orchestrator Instance ID is ${instanceID}`);

let functionID = "POST Reports Orchestrator";

try {
    // Make the POST request to retrieve the token
    const tokenResponse = await axios.post(logicAppURL, {
        requestType: "GET_TOKEN",
        functionID: functionID,
    });

    // Check if token was successfully retrieved
    if (tokenResponse.data && tokenResponse.data.token) {
        //log("Token successfully retrieved");
        return tokenResponse.data.token;
    } else {
        //log("Token could not be retrieved. Functions will generate their own token");
        await mandrillGeneralError(log, "Error retrieving token on POST Reports Orchestrator Token Manager function app in Azure.");
        return ""; // Return empty token if retrieval fails
    }

} catch (error) {
    //log(`Error retrieving token: ${error.message}`);
    await mandrillGeneralError(log, `Error retrieving token: ${error.message}`);
    throw error; // Throw the error so it's logged properly by Durable Functions
}
}
  });

JS, click event and class

In my website, when you click in a tag , an nav list open just above. This list closes when the user click in another part of the page (body), scroll the page (body) and when clicks again in the tag named “Produtos”.

I did 2 topics but i am with a problem with de last one

HTML:

  <div class="cabecalho-lista">
        <ul class="cabecalho__lista">
          <li class="cabecalho__item">
            <a class="cabecalho__item__link" href="index.html">Home</a>
          </li>
          <div class="cabecalho__item-produtos">
            <li class="cabecalho__item cabecalho__item__produtos">
              <input class="produtos-celular" type="checkbox" id="menu" />
              <label for="menu">
                <a
                  class="cabecalho__item__link"
                  id="link-produtos"
                  href="produtos.html"
                  >Produtos</a
                >
              </label>

              <ul class="lista-produtos invisivel">
                <li class="lista-produtos__item">
                  <a href="produtos.html#ignite">Linha Ignite</a>
                </li>
                <li class="lista-produtos__item">
                  <a href="produtos.html#elfbar">Linha Elfbar</a>
                </li>
                <li class="lista-produtos__item">
                  <a href="produtos.html#oxbar">Linha Oxbar</a>
                </li>
                <li class="lista-produtos__item">
                  <a href="produtos.html#lost">Linha Lost Mary</a>
                </li>
              </ul>
            </li>
          </div>
          <li class="cabecalho__item">
            <a class="cabecalho__item__link" href="contato.html">FAQ</a>
          </li>
        </ul>
      </div>

CSS:

.visivel {
  display: block;
}

.invisivel {
  display: none;
}

JS:

let checkBoxProdutos = document.querySelector("#menu");
let produtos = document.getElementById("link-produtos");

checkBoxProdutos.addEventListener("change", function () {
  x = window.matchMedia("(max-width: 849px)");
  if (x.matches) {
    if (this.checked) {
      listaProdutos.classList.add("visivel");
      listaProdutos.classList.remove("invisivel");

      // Para fechar a lista:
      let body = document.querySelector("body");
      body.addEventListener("click", function () {
        listaProdutos.classList.add("invisivel");
        listaProdutos.classList.remove("visivel");
        checkBoxProdutos.checked = true;
      });
      body.addEventListener("mousewheel", function () {
        listaProdutos.classList.add("invisivel");
        listaProdutos.classList.remove("visivel");
      });

      produtos.addEventListener("click", function () {
        alert("ola");
        listaProdutos.classList.add("invisivel");
        listaProdutos.classList.remove("visivel");
      });
    } else {
      listaProdutos.classList.add("invisivel");
      listaProdutos.classList.remove("visivel");
    }
  }
});

I tried with the else, thats recognizes when the check input changes but doesnt work, so i did an click listener in the tag. Just the alert works.
In the case of the else, even the alert doesnt work

Stripe payment api sending an OPTIONS request instead of a POST

This is where the payment fails, the options request.


const appearance = {
    theme: 'night',
};

const stripe = Stripe('pk_test_51PccgFRo1v56iAOxEVEimciGkyyLOcjVE98T3rqOHLuvx28QNxI8sfvYN0zwSka8vLRIIIEdkOHorjb5OJUdwhIx00VRs64Seu');

// Set up Stripe Elements
const elements = stripe.elements({appearance: {theme: 'night'}});

const card = elements.create('card' );
card.mount('#payment-element');

document.querySelector("#payment-form").addEventListener("submit", async (event) => {
    event.preventDefault();

    document.getElementById('submit').disabled = true;

    const name = document.querySelector("#name").value;
    const email = document.querySelector("#email").value;

    try {
        // Create the customer by sending data to the server
        const customerResponse = await fetch("http://localhost:4242/create-customer", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({ name, email }),
        });

        console.log(customerResponse);

        // Ensure the response is JSON
        if (!customerResponse.ok) {
            throw new Error("Failed to create customer.");
        }

        const customerData = await customerResponse.json();
        console.log("Customer created:", customerData);

        // Create a token for the card details
        const { token, error } = await stripe.createToken(card);

        if (error) {
            console.error('Error creating token:', error);
            alert('Failed to tokenize card details. Please try again.');
            document.getElementById('submit').disabled = false;
            return;
        }

        // Proceed to initialize the payment process
        await initializePayment(customerData.customerId, token.id);

    } catch (error) {
        document.querySelector("#error-message").textContent = error.message || "Failed to create customer.";
        console.error("Error:", error);
        document.getElementById('submit').disabled = false;
    }
});

async function initializePayment(customerId, tokenId) {
    try {
        // Create the checkout session
        const sessionResponse = await fetch("http://localhost:4242/create-checkout-session", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                customer: customerId, // Pass the customer ID to backend
                token: tokenId,       // Pass the tokenized card ID to backend
                priceId: 'price_1PfUDSRo1v56iAOxxLORAlv9'
            })
        });

        if (!sessionResponse.ok) {
            const errorData = await sessionResponse.json();
            throw new Error(errorData.message || `Failed to create checkout session.`);
        }

        const sessionData = await sessionResponse.json();
        window.location.href = sessionData.url; // Redirect to the Stripe Checkout or success page

    } catch (error) {
        document.querySelector("#error-message").textContent = error.message || "Failed to process payment.";
        console.error('Error:', error);
    } finally {
        document.getElementById('submit').disabled = false;
    }
}


public class Server {
    private static final Gson gson = new Gson();

    public static void main(String[] args) {
        port(4242);

        options("/*", (request, response) -> {
            String accessControlRequestHeaders = request.headers("Access-Control-Request-Headers");
            if (accessControlRequestHeaders != null) {
                response.header("Access-Control-Allow-Headers", accessControlRequestHeaders);
            }

            String accessControlRequestMethod = request.headers("Access-Control-Request-Method");
            if (accessControlRequestMethod != null) {
                response.header("Access-Control-Allow-Methods", accessControlRequestMethod);
            }

            return "OK";
        });

        before((request, response) -> {
            response.header("Access-Control-Allow-Origin", "*");  // Allow all origins
            response.header("Access-Control-Allow-Headers", "*");
            response.header("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
            response.header("Access-Control-Allow-Credentials", "true");
        });



        // Set Stripe API keys directly in the code
        Stripe.apiKey = "sk_test_yHMt2Vkexample";

        // Domain URL
        String domainUrl = "http://localhost:4242";

        get("/config", (request, response) -> {
            response.type("application/json");

            Map<String, Object> responseData = new HashMap<>();
            responseData.put("publishableKey", "pk_test_51PccgFRo1v56iAOxEVEimciGkyyLOcjVE98T3rqOHLuvx28QNxI8sfvYN0zwSka8vLRIIIEdkOHorjb5OJUdwhIx00VRs64Seu");
            responseData.put("proPrice", "price_1PfUDSRo1v56iAOxxLORAlv9");

            return gson.toJson(responseData);
        });

        // Fetch the Checkout Session to display the JSON result on the success page
        get("/checkout-session", (request, response) -> {
            response.type("application/json");

            String sessionId = request.queryParams("sessionId");
            Session session = Session.retrieve(sessionId);

            return gson.toJson(session);
        });

        post("/create-customer", (request, response) -> {
            response.type("application/json");
            Map<String, Object> requestData = gson.fromJson(request.body(), Map.class);
            String email = (String) requestData.get("email");
            String name = (String) requestData.get("name");

            try {
                CustomerCreateParams params = CustomerCreateParams.builder()
                        .setEmail(email)
                        .setName(name)
                        .build();
                Customer customer = Customer.create(params);

                Map<String, Object> responseData = new HashMap<>();
                responseData.put("customerId", customer.getId());
                responseData.put("email", customer.getEmail());
                responseData.put("name", customer.getName());
                return gson.toJson(responseData);
            } catch (StripeException e) {
                response.status(400);
                Map<String, Object> errorData = new HashMap<>();
                errorData.put("error", e.getMessage());
                return gson.toJson(errorData);
            }
        });

        post("/create-checkout-session", (request, response) -> {
            response.type("application/json");

            // Parse request body as JSON
            Map<String, Object> requestData = gson.fromJson(request.body(), Map.class);

            // Retrieve the priceId from the JSON payload
            String priceId = (String) requestData.get("priceId");

            // Create session parameters
            SessionCreateParams params = new SessionCreateParams.Builder()
                    .setSuccessUrl(domainUrl + "/success.html?session_id={CHECKOUT_SESSION_ID}")
                    .setCancelUrl(domainUrl + "/canceled.html")
                    .setMode(SessionCreateParams.Mode.SUBSCRIPTION)
                    .addLineItem(new SessionCreateParams.LineItem.Builder()
                            .setQuantity(1L)
                            .setPrice(priceId)
                            .build()
                    )
                    .build();

            try {
                Session session = Session.create(params);
                response.status(303); // HTTP 303 See Other
                response.redirect(session.getUrl());
                return ""; // Returning an empty string to indicate no body content
            } catch (Exception e) {
                Map<String, Object> messageData = new HashMap<>();
                messageData.put("message", e.getMessage());
                Map<String, Object> responseData = new HashMap<>();
                responseData.put("error", messageData);
                response.status(400);
                return gson.toJson(responseData);
            }
        });


        post("/customer-portal", (request, response) -> {
            String sessionId = request.queryParams("sessionId");

            // Retrieve the Checkout Session to get the customer ID
            Session checkoutSession;
            try {
                checkoutSession = Session.retrieve(sessionId);
            } catch (Exception e) {
                response.status(400);
                return gson.toJson(Collections.singletonMap("error", "Failed to retrieve session: " + e.getMessage()));
            }

            String customer = checkoutSession.getCustomer();

            // Create a Billing Portal session
            com.stripe.param.billingportal.SessionCreateParams params =
                    new com.stripe.param.billingportal.SessionCreateParams.Builder()
                            .setReturnUrl(domainUrl + "/account") // Redirect to your account page after managing billing
                            .setCustomer(customer)
                            .build();
            com.stripe.model.billingportal.Session portalSession;
            try {
                portalSession = com.stripe.model.billingportal.Session.create(params);
            } catch (Exception e) {
                response.status(400);
                return gson.toJson(Collections.singletonMap("error", "Failed to create billing portal session: " + e.getMessage()));
            }

            // Redirect to the billing portal
            response.redirect(portalSession.getUrl(), 303);
            return "";
        });


        post("/webhook", (request, response) -> {
            String payload = request.body();
            String sigHeader = request.headers("Stripe-Signature");
            String endpointSecret = "your_webhook_secret"; // Replace with your actual webhook secret

            Event event;
            try {
                event = Webhook.constructEvent(payload, sigHeader, endpointSecret);
            } catch (SignatureVerificationException e) {
                response.status(400);
                return gson.toJson(Collections.singletonMap("error", "Invalid signature"));
            }

            // Handle the event
            switch (event.getType()) {
                case "checkout.session.completed":
                    // Handle successful payment
                    System.out.println("Checkout Session completed: " + event.getDataObjectDeserializer().getObject().toString());
                    response.status(200);
                    break;
                case "invoice.payment_succeeded":
                    // Handle successful payment for invoices
                    System.out.println("Invoice payment succeeded: " + event.getDataObjectDeserializer().getObject().toString());
                    response.status(200);
                    break;
                case "invoice.payment_failed":
                    // Handle failed payment for invoices
                    System.out.println("Invoice payment failed: " + event.getDataObjectDeserializer().getObject().toString());
                    response.status(200);
                    break;
                case "customer.subscription.created":
                    // Handle subscription creation
                    System.out.println("Subscription created: " + event.getDataObjectDeserializer().getObject().toString());
                    response.status(200);
                    break;
                case "customer.subscription.deleted":
                    // Handle subscription cancellation
                    System.out.println("Subscription canceled: " + event.getDataObjectDeserializer().getObject().toString());
                    response.status(200);
                    break;
                default:
                    response.status(200);
                    System.out.println("Unhandled event type: " + event.getType());
                    break;
            }

            return "";
        });
    }
}

So this error is caused when initializepayment function executes, but stripe does not accept OPTIONS request due to AWS constraint, based on my javascript is there anything I can do to prevent this from happening because I have my app running on PORT 8443. I can see the customer creation happen on stripe, but it fails to mak the payment.

Can `postMessage` messages get lost/dropped e.g. if recipient’s main thread is coincidentally blocked at the time it should have received it?

Context:

I’m tracking down a hard-to-replicate bug related to messages between frames. One thing I’m mildly suspicious of is that messages between the main frame and an iframe are sometimes not being sent successfully. I.e. messages are possibly being “dropped” in rare cases.

Question:

Is there any spec-level guarantee that a message sent with postMessage will be received by the target frames, assuming there’s no bugs in my code?

For example, if the recipient frame happens to be unresponsive (e.g. due to a long computation which freezes the main thread) at the time that it would have received the message event, could that cause the message event to be lost? Or would is it guaranteed to be “queued” and eventually received by the window once the main thread is freed up.

Example Code:

In my test code below, the messages are not dropped by the child, despite several several seconds of blocking code which runs while it is being sent messages. Once the child finishes the heavy computation, it processes the full backlog of messages.

Note that I was only able to test this in Chrome, because as of writing Firefox puts a sandboxed iframe on the same thread as the main thread.

let iframe = document.createElement("iframe");
iframe.sandbox = "allow-scripts";
iframe.srcdoc = `
    <script>
      window.addEventListener('message', (event) => {
        console.log('Child received:', event.data);
      });
      setInterval(() => {
        console.log('Child: Starting heavy processing');
        const startTime = Date.now();
        while (Date.now() - startTime < 5000) {
          // Heavy loop for 5 seconds
        }
        console.log('Child: Finished heavy processing');
      }, 10000);
    </script>
  `;
document.body.append(iframe);

// Send a message every second
let messageIndex = 0;
setInterval(() => {
  const message = `Message ${messageIndex}`;
  console.log('Parent sending:', message);
  iframe.contentWindow.postMessage(message, '*');
  messageIndex++;
}, 1000);

Notes:

  • I’d prefer answers which reference specifications, since this would allow me to file bug reports on browser engines if needed.
  • I’ve noticed that if I have the debugger paused in the recipient frame, then all messages are lost. After unpausing, the messages are never received.
  • If there are no spec-level guarantees in this area, I’m also interested in any info on browser-engine-specific behavior, if anyone has any info on that.

Simple JavaScript on click event is not working [closed]

There is a CSS file and js file that was copied for a custom particle engine background. I can post them if this file isn’t the problem but they are extremely complex. There is another CSS file to style the html code below

The code is below.

function handleClick() {
  alert("Button clicked!");
}
<!-- File-->
<!DOCTYPE html>
<html lang="en-US">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>homePage</title>

  <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">


  <script src="../static/background.js" defer></script>
  <script src="https://code.createjs.com/1.0.0/easeljs.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.1/gsap.min.js"></script>

  <link rel="stylesheet" href="../static/background1.css">
  <link rel="stylesheet" href="../static/signInPage.css">
</head>

<body>

  <!-- Heading's Color ans size -->
  <h1>

    <span class="welcome">Hello &amp; Welcome To:</span>
    <span class="redRat"> THE RED RAT'S ACRCHIVES </span>

  </h1>


  <!-- Paragraph text -->
  <p class="welcomeMessage"> This is a collection containing the most popular browser games from all over the internet with games that are old and new. <br> I hope you will enjoy and share with your friends.<br> </p>
  <br>
  <p class="createAccountMessage"> Please sign in or create an account to access the website</p>

  <!-- Log In Buttons-->
  <div class="createAccountButton">
    <button onclick="handleClick()" id="createAccount" type="button" class="btn btn-outline-light">Create Account</button>
  </div>

  <div class="signInButton">
    <button type="button" class="btn btn-outline-light">Sign In</button>
  </div>

  <!-- Paragraph text -->
  <p class="contactInfo"> email me at [email protected] with any feedback, recommendations, or errors you encounter </p>

  <canvas id="projector" width="800" height="600"></canvas>


</body>

</html>

I have tried using event listeners and putting the js code in other files. I tried debugging and checking for errors as well as other basic js functions. I have no idea. I was expecting a basic js alert when the createAccount button is clicked. The alert function was created to make sure Js code generally works in my program.

Simple Java Script on click event is not working

There is a css file and js file that was copied for a custom particle engine background. I can post them if this file isn’t the problem but they are extremely complex. There is another css file to style the html code below

The code is below.

function handleClick() {
  alert("Button clicked!");
}
<!-- File-->
<!DOCTYPE html>
<html lang="en-US">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>homePage</title>

  <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">


  <script src="../static/background.js" defer></script>
  <script src="https://code.createjs.com/1.0.0/easeljs.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.1/gsap.min.js"></script>

  <link rel="stylesheet" href="../static/background1.css">
  <link rel="stylesheet" href="../static/signInPage.css">
</head>

<body>

  <!-- Heading's Color ans size -->
  <h1>

    <span class="welcome">Hello &amp; Welcome To:</span>
    <span class="redRat"> THE RED RAT'S ACRCHIVES </span>

  </h1>


  <!-- Paragraph text -->
  <p class="welcomeMessage"> This is a collection containing the most popular browser games from all over the internet with games that are old and new. <br> I hope you will enjoy and share with your friends.<br> </p>
  <br>
  <p class="createAccountMessage"> Please sign in or create an account to access the website</p>

  <!-- Log In Buttons-->
  <div class="createAccountButton">
    <button onclick="handleClick()" id="createAccount" type="button" class="btn btn-outline-light">Create Account</button>
  </div>

  <div class="signInButton">
    <button type="button" class="btn btn-outline-light">Sign In</button>
  </div>

  <!-- Paragraph text -->
  <p class="contactInfo"> email me at [email protected] with any feedback, recommendations, or errors you encounter </p>

  <canvas id="projector" width="800" height="600"></canvas>


</body>

</html>

I have tried using event listeners and putting the js code in other files. I tried debugging and checking for errors as well as other basic js functions. I have no idea. I was expecting a basic js alert when the createAccount button is clicked. The alert function was created to make sure Js code generally works in my program.

Swiper does not work in separated Tab in PHP

In the <div class="B"> section, if I write:

<?php for ($i = 1; $ i <= 1; $i++) : ?>

it works, however this:

<?php for ($i = 1; $i <= 7; $i++) : ?> 

does not work like a photo.

Somebody knows why this happens?

[enter image description here](https://i.sstatic.net/nN7WnbPN.png)

My PHP code:

<?php

/**
 * Template Name: xxxxxx
 */

?>

<?php get_header(); ?>
<main>

    <section class="sec-t">
        <div class="cnt">
            <div class="store_info">
                <div class="A">
                    <div class="about-shop">
                        <div>
                            <div class="swiper-container main-image-container">
                                <div class="swiper-wrapper">
                                    <?php for ($i = 1; $i <= 17; $i++) : ?>
                                        <div class="swiper-slide">
                                            <img src="<?php imgurl(); ?>/store/xxx_store/xxx_store_inside/xxx_store_inside<?php echo $i; ?>.jpg" alt="xxx<?php echo $i; ?>">
                                        </div>
                                    <?php endfor; ?>
                                </div>
                                <?php
                                if ($i > 2): ?>
                                    <div class="swiper-pagination"></div>
                                <?php endif; ?>
                                <div class="swiper-button-next"></div>
                                <div class="swiper-button-prev"></div>
                            </div>
                        </div>
                        <div class="swiper-container seat-image-container">
                            <div class="swiper-wrapper">
                                <?php for ($i = 1; $i <= 7; $i++) : ?>
                                    <div class="swiper-slide">
                                        <img src="<?php imgurl(); ?>/store/xxx_store/xxx_c/xxx_c<?php echo $i; ?>.jpg" alt="c_seat_image<?php echo $i; ?>">
                                    </div>
                                <?php endfor; ?>
                            </div>
                            <?php
                            if ($i > 2): ?>
                                <div class="swiper-pagination"></div>
                            <?php endif; ?>
                            <div class="swiper-button-next"></div>
                            <div class="swiper-button-prev"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="B">
            <div class="cnt">
                    <div class="swiper-container seat-image-container">
                        <div class="swiper-wrapper">
                            <?php for ($i = 1; $i <= 7; $i++) : ?>
                                <div class="swiper-slide">
                                    <img src="<?php imgurl(); ?>/store/xxx_store/xxx_c/xxx_c<?php echo $i; ?>.jpg" alt="c_seat_image<?php echo $i; ?>">
                                </div>
                            <?php endfor; ?>
                        </div>
                        <?php

                        if ($i > 2): ?>
                            <div class="swiper-pagination2"></div>
                        <?php endif; ?>
                        <div class="swiper-button-next2"></div>
                        <div class="swiper-button-prev2"></div>
                    </div>
                </div>
            </div>
        </div>
        </div>

        </div>
    </section>

</main>

<script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script>


<?php get_footer(); ?>

My main.js script:

document.addEventListener('DOMContentLoaded', function() {
    // When you click tab1
    document.getElementById('tab1').addEventListener('click', function() {
        document.querySelector('.A').style.display = 'block';
        document.querySelector('.B').style.display = 'none';
        // document.querySelector('.C').style.display = 'none';
        document.querySelector('#tab1').classList.remove('off');
        document.querySelector('#tab2').classList.remove('on');
        document.querySelector('#tab3').classList.remove('on');
        document.querySelector('#tab1').classList.add('on');
        document.querySelector('#tab2').classList.add('off');
        document.querySelector('#tab3').classList.add('off');
    });

    // When you click tab2
    document.getElementById('tab2').addEventListener('click', function() {
        document.querySelector('.A').style.display = 'none';
        document.querySelector('.B').style.display = 'block';
        // document.querySelector('.C').style.display = 'none';
        document.querySelector('#tab1').classList.remove('on');
        document.querySelector('#tab2').classList.remove('off');
        // document.querySelector('#tab3').classList.remove('on');
        document.querySelector('#tab1').classList.add('off');
        document.querySelector('#tab2').classList.add('on');
        // document.querySelector('#tab3').classList.add('off');
    });


});


document.addEventListener('DOMContentLoaded', function() {

    var swipers = document.querySelectorAll('.swiper-container');

    swipers.forEach(function(swiperContainer) {
        var slideCount = swiperContainer.querySelectorAll('.swiper-slide').length;

        if (slideCount <= 1) {
            swiperContainer.querySelector('.swiper-button-next').style.display = 'none';
            swiperContainer.querySelector('.swiper-button-prev').style.display = 'none';
        }

        new Swiper(swiperContainer, {
            loop: slideCount > 1,
            slidesPerView: 1,
            centeredSlides: false,
            effect: 'fade',
            pagination: {
                el: swiperContainer.querySelector('.swiper-pagination'),
                type: 'fraction',
            },
            fadeEffect: {
                crossFade: true
            },
            navigation: {
                nextEl: swiperContainer.querySelector('.swiper-button-next'),
                prevEl: swiperContainer.querySelector('.swiper-button-prev'),
            },
        });
    });
});

I tried this:

var swipers = document.querySelectorAll('.swiper-container');

but nothing happens.

Messages are not ordering correctly in Firebase(JS, HTML)

I created firebase website using JS and frontend

Eveything works correctly expect this one thing. My chats are not ordering by date correctly
This is what i see now:
Anastasia: Hello! (9/17/2024, 10:46:47 PM)
Anastasia: How are you? (9/17/2024, 10:47:06 PM)
Anastasia: Hallo (9/17/2024, 11:41:27 PM)
User2: Yep (9/17/2024, 10:49:16 PM)
User2: Good, thanks ! (9/17/2024, 10:47:23 PM)
User2: Hey (9/17/2024, 10:46:55 PM)
What I want to see:
User2: Hey (9/17/2024, 10:46:55 PM)
Anastasia: Hello! (9/17/2024, 10:46:47 PM)
Anastasia: How are you? (9/17/2024, 10:47:06 PM)
User2: Good, thanks ! (9/17/2024, 10:47:23 PM)
User2: Yep (9/17/2024, 10:49:16 PM)
Anastasia: Hallo (9/17/2024, 11:41:27 PM)

My code

document.addEventListener("DOMContentLoaded", () => {
  firebase.auth().onAuthStateChanged((user) => {
    if (user) {
      const chatId = new URLSearchParams(window.location.search).get("chatId");
      if (!chatId) {
        console.error("Invalid or missing chatId in URL.");
        return;
      }

      // Retrieve messages ordered by timestamp
      const messagesRefForDisplay = firebase
        .database()
        .ref(`chats/${chatId}/messages`)
        .orderByChild("timestamp");
      // Use a regular reference for sending messages
      const messagesRefForSending = firebase
        .database()
        .ref(`chats/${chatId}/messages`);

      // Function to get username from user ID
      function getUsername(userId, callback) {
        const userRef = firebase.database().ref(`users/${userId}`);
        userRef.once("value", (snapshot) => {
          const userData = snapshot.val();
          callback(userData.username);
        });
      }
      function formatTimestamp(timestamp) {
        const date = new Date(timestamp);
        return date.toLocaleString(); // Customize the format if needed
      }

      // Load messages ordered by timestamp
      messagesRefForDisplay.on("child_added", (snapshot) => {
        const message = snapshot.val();
        getUsername(message.senderId, (username) => {
          const messageElement = document.createElement("div");
          messageElement.classList.add("message");
          const formattedTimestamp = formatTimestamp(message.timestamp);

          messageElement.innerHTML = `<span class="sender">${username}:</span> ${message.message} <span class="timestamp">(${formattedTimestamp})</span>`;
          document.getElementById("messages").appendChild(messageElement);

          // Auto scroll to the bottom after a new message is added
          document.getElementById("messages").scrollTop =
            document.getElementById("messages").scrollHeight;
        });
      });

      // Send message
      document.getElementById("sendMessage").addEventListener("click", () => {
        const messageInput = document.getElementById("messageInput");
        const messageText = messageInput.value.trim();
        if (messageText) {
          // Use the unfiltered messagesRef for sending
          messagesRefForSending
            .push({
              message: messageText,
              senderId: user.uid, // Use user.uid here
              timestamp: Date.now(),
            })
            .then(() => {
              console.log("Message sent successfully");
            })
            .catch((error) => {
              console.error("Error sending message:", error);
            });
          messageInput.value = ""; // Clear the input
        }
      });
    } else {
      console.log("User is not logged in.");
    }
  });
});

Vue JS change to-be-edited variable depending on parameter passed into function

Hi JS (and general) newbie here,

I’m currently trying to make simple webpage with Vue JS which has clickable content which results in that section expanding to reveal more content.

I did this with a boolean variable “expanded” which gets toggled on-click.

<q-card @click="expand_header()">
<div v-show="expanded">
export default {
  setup() {
    return {
      expanded: ref(false),
    };
  },
}
expand_header: function () {

      this.expanded = !this.expanded;

    },

However, because I am trying to add this functionality to multiple boxes, I wanted to abstract this functionality and pass a paramater when the function is called which will edit the corresponding variable, and I was wondering what the correct syntax would be.

Newbiew instincts told me to pass a number parameter into the function which will edit one of similar variables like so:

@click="expand_header(1)"
@click="expand_header(2)"
<div v-show="expanded1">content<div>
<div v-show="expanded2">content<div>

export default {
  setup() {
    return {
      expanded1: ref(false),
      expanded2: ref(false),
    };
  },
}
expand_header: function (num) {

      this.expanded[num] = !this.expanded[num];

    },

or so:

expand_header: function (num) {

      this.expanded + num = !this.expanded + num;

    },

however this is clearly not the correct syntax.

I was not sure where I could find documentation or guides on JS syntax for this type of problem, so any input or docu recommendation would be greatly appreciated!

Javascript html table get clicked cell value and column(th) ID

i am trying to get a clicked Table Cell value and corresponding Column ID (th.id)
i need in the $msg the following.

  • Clicked Cell Value (easy (e.target.innerHTML)
  • Get the cellIndex from the cell (td) (easy e.target.cellIndex)
  • corresponding column (th) ID for the same e.target.cellIndex
    *** when i comment the foreach the code work.
    the foreach apparently not working
    Please help
    function onTableCellClicked(e){
     //  alert('table cell clicked value ='+e.target.innerHTML);
       if(e.target.innerHTML && window.chrome.webview){
        $ind=e.target.cellIndex
        $Msg=e.target.innerHTML
       var TTH = document.getElementById('NGTable1 th');
       TTH.forEach(function(th) {
         if (th.cellIndex==$ind){$Msg=$Msg+'|'+th.id}
        })
       window.chrome.webview.postMessage($Msg);
     }  
   }

How to Remove Hash from index.js and index.runtime.js in Parcel with parcel-namer-hashless?

I’m working on a TypeScript project where I’m using Parcel v2.x for bundling, and I want to remove the hash from the output filenames (particularly from index.js and index.runtime.js).

I’ve been using the parcel-namer-hashless plugin, and while it successfully removes the hash from most of my files (like favicon.ico, esp32.js, etc.), I’m still encountering issues with the index.js and index.runtime.js files. They continue to have a hash in their filenames, despite my efforts to configure the plugin to remove them.

Here’s what I’ve tried so far:

Configured parcel-namer-hashless in package.json:

{
  "name": "typescript",
  "version": "1.0.0",
  "description": "This an example of using esptool-js with parcel and typescript",
  "source": "src/index.html",
  "scripts": {
    "genDocs": "cd ../.. && npm run genDocs && mkdir -p examples/typescript/dist && cp -r docs examples/typescript/dist && cd examples/typescript",
    "dev": "npm run clean && npm run genDocs && parcel src/index.html",
    "build": "npm run clean && npm run genDocs && parcel build src/index.html --no-optimize --public-url ./",
    "clean": "rimraf dist .parcel-cache",
    "test": "echo "Error: no test specified" && exit 1",
    "postbuild": "mv dist/index.runtime.*.js dist/index.runtime.js"
  },
  "parcelIgnore": [
    "./docs/.+"
  ],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "parcel": "^2.8.3",
    "parcel-namer-hashless": "^1.0.6",
    "parcel-resolver-ignore": "^2.1.5",
    "rimraf": "^4.1.2",
    "typescript": "^4.9.4",
    "web-serial-polyfill": "^1.0.15"
  },
  "parcel-namer-hashless": {
    "include": [
      ".js$",           
      ".ico$"           
    ]
  }
}

Configured the .parcelrc file:

{
  "extends": "@parcel/config-default",
  "resolvers": [
    "parcel-resolver-ignore",
    "..."
  ],
  "namers": [
    "parcel-namer-hashless"
  ]
}

Cleared the Parcel cache and rebuilt multiple times.

Despite these efforts, index.runtime.js still havs hashes appended to them. The build output looks like this:

dist/index.runtime.298534a0.js

All other files are correctly renamed without hashes.

I also tried adding a post-build script to manually rename the files, but I’d prefer to have a cleaner solution within Parcel if possible.
My Questions:

How can I ensure that index.runtime.js are generated without hashes using Parcel and parcel-namer-hashless?
Is there a better way to configure Parcel or the parcel-namer-hashless plugin to handle runtime files?
Is there a specific reason why Parcel insists on adding a hash to runtime files, and how can this behavior be overridden?

Any advice or suggestions would be greatly appreciated. Thanks in advance!

I also tried it with a custom-namer.js with the same output:

const { Namer } = require('@parcel/plugin');

module.exports = new Namer({
  async name({ bundle }) {
    const entryAsset = bundle.getMainEntry();

    // Handle the main HTML or JS entry point (index)
    if (entryAsset && entryAsset.filePath.includes('index')) {
      // Check if it's a runtime file (Parcel auto-generates runtime bundles)
      if (bundle.type === 'js' && !bundle.isInline && bundle.needsStableName && bundle.isSplittable === false) {
        // Ensure the runtime script is named without a hash
        return `index.runtime.js`;
      }
      
      // For regular 'index.js' or 'index.html'
      return `index.${bundle.type}`;
    }

    // For all other entry points, use the original file name without hash
    if (entryAsset) {
      const originalName = entryAsset.filePath.split('/').pop().split('.')[0]; // Get original name without extension
      return `${originalName}.${bundle.type}`;
    }

    // Fallback for other dynamically generated chunks or assets
    const id = bundle.id.slice(0, 8); // Shorten bundle ID to 8 characters for uniqueness
    return `bundle-${id}.${bundle.type}`;
  }
});

How can I modify my multi-item carousel to slightly show the next item? (Bootstrap 5)

I have a multi-item carousel in Bootstrap 5.
Four items are visible on screen, and the slide allows to move forward one item at a time.

What I would like to do is to show a bit of the next item on screen (about 10% of it). So the user can see what’s coming. That is, without ceasing to have the four main items centered on screen.

I have seen examples of carousels with one item per slide that can do this. But I haven’t been able to make it with a multi-item carousel.

This is an example of what I have: https://codepen.io/Leticia-Techera/pen/KKjjoGB

let items = document.querySelectorAll('.carousel .carousel-item')

items.forEach((el) => {
    const minPerSlide = 4
    let next = el.nextElementSibling
    for (var i=1; i<minPerSlide; i++) {
        if (!next) {
            // wrap carousel by using first child
            next = items[0]
        }
        let cloneChild = next.cloneNode(true)
        el.appendChild(cloneChild.children[0])
        next = next.nextElementSibling
    }
})
.carousel-control-next, .carousel-control-prev {
    position: unset;
    width: 5%;
}
.buttons-container{
    display: flex;
}
.carousel-control-prev-icon, .carousel-control-next-icon{
    background-color:black;
}

@media (max-width: 767px) {
    .carousel-inner .carousel-item>div {
        display: none;
    }

    .carousel-inner .carousel-item>div:first-child {
        display: block;
    }
}

.carousel-inner .carousel-item.active,
.carousel-inner .carousel-item-next,
.carousel-inner .carousel-item-prev {
    display: flex;
}

/* medium and up screens */
@media (min-width: 768px) {

    .carousel-inner .carousel-item-end.active,
    .carousel-inner .carousel-item-next {
        transform: translateX(25%);
    }

    .carousel-inner .carousel-item-start.active,
    .carousel-inner .carousel-item-prev {
        transform: translateX(-25%);
    }
}

.carousel-inner .carousel-item-end,
.carousel-inner .carousel-item-start {
    transform: translateX(0);
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container text-center my-3">
    <div class="row mx-auto my-auto justify-content-center">
        <div id="recipeCarousel" class="carousel slide" data-bs-ride="carousel">
            <div class="carousel-inner" role="listbox">
                <div class="carousel-item active">
                    <div class="col-md-3">
                        <div class="card ratio ratio-1x1 bg-primary">
                        </div>
                    </div>
                </div>
                <div class="carousel-item">
                    <div class="col-md-3">
                        <div class="card ratio ratio-1x1 bg-secondary">
                        </div>
                    </div>
                </div>
                <div class="carousel-item">
                    <div class="col-md-3">
                        <div class="card ratio ratio-1x1 bg-success">
                        </div>
                    </div>
                </div>
                <div class="carousel-item">
                    <div class="col-md-3">
                        <div class="card ratio ratio-1x1 bg-danger">
                        </div>
                    </div>
                </div>
                <div class="carousel-item">
                    <div class="col-md-3">
                        <div class="card ratio ratio-1x1 bg-warning">
                        </div>
                    </div>
                </div>
                <div class="carousel-item">
                    <div class="col-md-3">
                        <div class="card ratio ratio-1x1 bg-info">
                        </div>
                    </div>
                </div>
            </div>
            <div class="buttons-container">
                <a class="carousel-control-prev bg-blue w-aut" href="#recipeCarousel" role="button" data-bs-slide="prev">
                    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                </a>
                <a class="carousel-control-next bg-blue w-aut" href="#recipeCarousel" role="button" data-bs-slide="next">
                    <span class="carousel-control-next-icon" aria-hidden="true"></span>
                </a>
            </div>
        </div>
    </div>
</div>

Is there a way to modify it to achieve what I want?
Thanks!!

CORS error while trying to run an AWS lambda function

I’m trying to run a lambda function from my front-end website but I keep getting a CORS error.

The front-end code that should contact the lambda function is the following:

    const handleSubmit = async (e) => {
        e.preventDefault();
        setIsSubmitting(true);
        setSubmitMessage('');

        try {
            const response = await fetch('https://foobar.lambda-url.eu-west-2.on.aws/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(formData),
            });

            if (response.ok) {
                setSubmitMessage('Your request has been submitted successfully!');
                setFormData({
                    name: '',
                });
            } else {
                throw new Error('Form submission failed');
            }
        } catch (error) {
            console.error('Error:', error);
            setSubmitMessage('An error occurred. Please try again later.');
        } finally {
            setIsSubmitting(false);
        }
    };

The error is the following:

Access to fetch at 'https://foobar.lambda-url.eu-west-2.on.aws/' from origin 'https://my-website.amplifyapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.Understand this error
index.js:29 
        
POST https://foobar.lambda-url.eu-west-2.on.aws/ net::ERR_FAILED

index.js:50 Error: TypeError: Failed to fetch
    at index.js:29:36

CORS are active on AWS. The thing that I find strange is that the request on the chrome network tab display “Provisional Header are shown”:

enter image description here

And if I use the same parameter but using the terminal and curl the call goes through without any problem, for example:

curl -X POST 'https://foobar.lambda-url.eu-west-2.on.aws/' 
-H 'Content-Type: application/json' 
-d '{"name":"test test"}'

Here’s the lambda function:

import { SES } from "@aws-sdk/client-ses";
const ses = new SES({ region: 'eu-west-2' });

export async function handler(event) {
  if (event.httpMethod === "OPTIONS") {
    return {
      statusCode: 200,
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Headers": "Content-Type",
        "Access-Control-Allow-Methods": "POST, OPTIONS",
      },
      body: JSON.stringify({ message: "Preflight check successful" }),
    };
  }

  let formData;

  if (event.body) {
    try {
      formData = JSON.parse(event.body);
    } catch (error) {
      console.error("Error parsing event body:", error);
      return {
        statusCode: 400,
        headers: {
          "Access-Control-Allow-Origin": "*",
        },
        body: JSON.stringify({ message: "Invalid JSON" }),
      };
    }
  } else {
    return {
      statusCode: 400,
      headers: {
        "Access-Control-Allow-Origin": "*",
      },
      body: JSON.stringify({ message: "No body provided" }),
    };
  }

  const params = {
    Destination: { ToAddresses: ["my-email-address"] },
    Message: {
      Body: { Text: { Data: JSON.stringify(formData, null, 2) } },
      Subject: { Data: "form info" },
    },
    Source: "some-user",
  };

  try {
    await ses.sendEmail(params);

    return {
      statusCode: 200,
      body: JSON.stringify({ message: "Email sent successfully" }),
    };
  } catch (error) {
    console.error(error);
  } finally {
    console.log("finished");
  }
}

What am I missing?

Prevent window.close after redirect to a custom protocol URL

I need to redirect a page to an URL, using a custom protocol, to open a local application. After the redirection is done and the application is called, the page needs to be closed using window.close() function.

If the protocol of the redirection is not recognized, nor the user explicitly allowed this protocol, an warning popup is presented by the browser (not my code), informing the not recognized protocol and asking the user to confirm the opening of the application.

enter image description here

The user also have the option of click in “always allow” (the explicity consent) to prevent the warning popup be presented in the next time.

My original code is this:

<html>

<head>
    <script src="https://code.jquery.com/jquery-3.7.1.slim.js"
        integrity="sha256-UgvvN8vBkgO0luPSUl2s8TIlOSYRoGFAX4jlCIm9Adc=" crossorigin="anonymous"></script>
</head>

<script>
    $(document).ready(function () {
        window.location = "custom_app_protocol://commands/goto?some_parms";
        window.close();
    });
</script>
<body>
    Redir test.
</body>
</html>

This code above works fine if the warning popup is not presented (protocol recognized or explicit consent already given). Then, the application is called and the page is closed.

But, if the warning popup is presented, the page is closed without perform the app call.

An option would be include a timeout after the call:

$(document).ready(function () {
    //window.location = "custom_app_protocol://commands/goto?some_parms";
    window.location = "cherwellclient://commands/goto?rectype%3DDevelopmentRequest%26PublicID%3D1617";
    setTimeout(function () {
        window.close();
    }, (5000));
});

But, if the user doesn’t click in the warning popup before the timeout trigger the page closing command, the page will be closed without open the app.

So, my question is: there is an way to perform the window.close() only after the warning popup be closed?

Average problem in mixing line chart and bar chart

stack bilitz url = https://stackblitz.com/edit/stackblitz-starters-ws9ujj?file=src%2Fapp%2Fperformance-chart%2Fperformance-chart.component.ts

It should be exactly like this image, but when I change the data, it shifts directly and I did it with transformation scale to show it correctly. Otherwise, if you change the data a little, it will immediately get corrupted.

Temporary image made with smooth transform.

I tried to give the width with calculator but I didn’t get any results