Executing a JavaScript function upon loading the Pug template and utilizing it to set a parameter in the

My objective is to trigger a JS function from a pug template that will store an item in the localStorage. The value of this item will be a parameter passed to the pug template labeled as "token".

I have looked at similar questions in the past and found inspiration from answers that are somewhat similar, such as:

  • Pug call js function from another file inside template
  • Express / Jade / Pug: Calling a javascript object's functions

Here is the code I ended up with:

users.js

import setToken from "../src/setToken";

router.post("/signin", (req, res) => {
    ...

    cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: function(result) {
            res.render("congrats", {
                title: "Congrats",
                token: result.getAccessToken().getJwtToken(),
                setToken: setToken
            });
        },
        onFailure: function(err) {
            next(err);
        }
    });
});

setToken.js

export default (token) => {
    console.log("::: setToken :::");
    localStorage.setItem("cognitoToken", token);
};

congrats.pug

extends layout

block scripts
    script
        |   var setToken = #{setToken};
        |   setToken(#{token})

block content
    ...

layout.pug includes a client-side JS script with a function called storeToken. I also tried calling this function but nothing happened.

Despite rendering correctly within the <script> tag of my template, the JS code doesn't execute, and nothing gets stored in localStorage. I'm not sure if passing the function reference during template rendering is the best approach or if it should be included on the client side.

EDIT

After inspecting the markup, I noticed that my JS code renders properly within the <script> tag of my template:

<script>
    console.log("token: ", **token value**);
    var setToken = function (token) {
        console.log(&quot;::: setToken :::&quot;);
        localStorage.setItem(&quot;cognitoToken&quot;, token);
    };
    setToken(**token value**)
</script>

EDIT 2

In my case, I have 4 pug pages that load sequentially based on the user's progress while registering for Cognito. Injecting JS into the other 3 templates works fine. For example:

block scripts
    script(type="text/javascript")
        |   var page = "confirm";

I can access the variable 'page' in the console and get the output "confirm". However, when attempting the same in my congrats.pug template, it returns undefined. This issue might be related to how the pages are rendered. Comparing one that works and one that doesn't, there doesn't seem to be any noticeable differences, although I could be missing something here.

/*
 * Works
 */
router.post("/confirm", (req, res, next) => {
    const { confirm } = req.body;

    cognitoUser.confirmRegistration(confirm, true, function(err, result) {
        if (err) {
            next(err);
        }
        res.render("signin", {
            title: "Signin"
        });
    });
});
//////////

/*
 * Doesn't work
 */
router.post("/signin", (req, res) => {
    const { username, password } = req.body;
    const authenticationData = {
        Username: username,
        Password: password
    };
    const authenticationDetails = new AuthenticationDetails(authenticationData);

    cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: function(result) {
            res.render("congrats", {
                title: "Congrats",
                token: result.getAccessToken().getJwtToken(),
                setToken: setToken
            });
        },
        onFailure: function(err) {
            next(err);
        }
    });
});
//////////

Answer №1

Ultimately, the issue seemed to revolve around how I passed a function reference to my template. Removing that resolved the JavaScript problem I was experiencing.

When it came to setting the token, I felt that using a function in an external file added unnecessary complexity. As a result, I opted to directly insert the necessary code within a <script> tag in the template. Below is the revised template that now functions as intended:

extends layout

block scripts
    script(type="text/javascript").
        var token = "#{token}";
        localStorage.setItem("cognitoToken", token);

block content
    .container
        .col-md-6.mx-auto.text-center
            .header-title
            h1.wv-heading--title= title
        .row
            .col-md-4.mx-auto
                p You have successfully authenticated with AWS Cognito, your access token is
                    strong #{token}

I would like to acknowledge the helpful insights from this answer which guided me on referencing a pug param within a <script> tag

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to control the text animation loop on iTyped, both starting and stopping it?

Currently utilizing React, MUI, along with iTyped The animation implemented involves backspacing text and typing the next word in a specified array until reaching the final word. I am looking to enable a click function on the div containing this animation ...

Instructions for deactivating a drop-down list using radio buttons in JavaScript

I am working on a project where I have 3 radio buttons and 3 different combo boxes in my HTML. I want to use JavaScript to enable/disable the combo boxes based on which radio button is selected. For example, when the G1 radio button is clicked, I want on ...

Methods for activating touch-like scrolling through the use of mouse grabbing and dragging

Let me show you a simple illustration of the task I'm attempting to accomplish: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> ...

Regular expression: Strip the brackets from a portion of the text

I have a JavaScript application where I need to manipulate strings. The text follows this structure: It might begin with a prefix in square brackets [prefix]. I have to preserve this prefix with the brackets. Next comes [whatever string], in this case I ...

Transmitting data from JQuery to PHP script

In my current setup, I am utilizing JavaScript to retrieve a JSON array from a PHP file: <script type="text/javascript" language="javascript" > $(document).ready(function() { var dataTable = $('#employee-grid'). ...

Executing a Ruby method on a server using JavaScript - A guide

I'm facing a seemingly simple issue that I can't seem to find a clear solution for anywhere. Essentially, I have a JavaScript application hosted on a server that requires passing information between the JS app and a Rails-built server. The proces ...

"The concept of hoisting in JavaScript and its impact on global

Is there a way to set the variable "username_show" from this PouchDB document? I attempted using hoisting, but it seems that I may need to move the global variable outside of the data structure and then outside of the function. var db = new PouchDB ...

Does the exchange of information between the frontend and backend exclusively occur through routes?

I'm currently developing a Vue.js/Express fullstack web application, and I understand that endpoints can be defined on the server like so: app.get('/', function (req, res) { res.send('GET request to the homepage') }) These end ...

Enhancing user accessibility can be achieved by either utilizing alt tags on images or aria labels on parent buttons

When using a functional image as a button or link, it is typically marked up with an img tag wrapped by a button tag or anchor tag. If there is no accompanying text for the image, a text alternative needs to be provided for assistive technology. There are ...

The capacity to rotate div containers, adjust their dimensions, and engage with the content within

I'm attempting to design small clickable div boxes that flip 180° when clicked to reveal interactive content. This includes the ability to click links, copy text, or manipulate the content with additional buttons. Although I've successfully ach ...

Restricting the fields in a $lookup operation in MongoDB

My Mongo object follows the schema provided below. { "_id" : "59fffda313d02500116e83bf::5a059c67f3ff3b001105c509", "quizzes" : [ { "topics" : [ ObjectId("5a05a1e1fc698f00118470e2") ], " ...

Why my attempts to alter numerous CSS elements using JQuery are failing?

Here's the code snippet I'm working with: var showThis = $(this).attr('id'); // div0, div1, div2 etc. $('#' + showThis).attr('style', 'background-color: #063 !important, height: 520px'); I am trying to mo ...

Navigating through a large number of distinct items in Three.JS

I have hit a roadblock in my project development. I am striving to create a level using various phong materials on objects of unique sizes and shapes. However, Three.JS's default texture handling causes them to stretch out and look distorted on meshes ...

Is it possible to delete a section of the URL within an anchor tag prior to the #anchor

My webpage contains a link that looks like this: <li class="jump"><a href="http://example.com/#about">About Me</a></li> I am interested in using jQuery to eliminate the 'http://example.com/' section of any URL found with ...

Turn off the feature of map scrolling on OpenStreetMaps

Is there a way to prevent mouse interactions and scrolling in an open maps iframe? I have already tried adding the attribute scrollwheel="false" to no avail. Are there any CSS methods to achieve this? <iframe id= "mapsource" scrollwheel="false" src="ht ...

The issue persists with Jquery's removeData function when used on a modal triggered by an href link in order to transmit $_GET

I am currently developing a website that dynamically populates a table from the database. Each row in the table contains a button that triggers a modal to display more details and allows for database updates. To pass the required values to the modal, I hav ...

Verify whether the text field is filled or not excluding the placeholder

How can I detect if a div is empty except for the placeholder element/value? Scenario 1: Div is empty <div id="textarea" contenteditable="true"> <span id="textarea-placeholder" data-text="Enter comment" ...

Create a compilation of file names in Dropzone.js for submission in a form

I have been diligently working on compiling a list of file names that are lined up for uploading in Dropzone.js. After scouring the forums for weeks, I finally stumbled upon a potential solution here: https://github.com/enyo/dropzone/issues/1652 My journe ...

Utilizing the change() and contains() functions with an HTML <select> element in jQuery

Currently, I am working on a feature where images change based on the value selected from a dropdown menu. The code provided below is a simplified version to convey the main idea. Here's the gist of what I have (feel free to ask any questions; please ...

Need help with creating a new instance in AngularJS? Unfortunately, the save method in CRUD is not getting the job done

Whenever I attempt to create a new task, nothing seems to happen and no request is being sent. What could be causing this issue? How can I go about troubleshooting it? Take a look at how it appears here Check out the $scope.add function below: var app ...