How to iniialize materialize css in my node project to use sidenav

I am working on a nodeJs app which has a main secssion. Within the main secssion i have a partial secssion called _header. I want to use materialize css in my app to bring a sidenav. But i am not able to intialize materialize css.

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const sidenav = document.querySelector('.sidenav');
        M.Sidenav.init(sidenav);
        });
</script>

This does not work.

How add events to Confluence calendar with JS API?

I’m trying to find any information on how I can create an event in Team Calendar in Confluence, but I can’t find anything useful for JS. The official documentation is missing, and there are only suggestions for workarounds, which do not suit me.

I’ve gone through all the possible documentation and advice that I could find online. It turned out to be insufficient. Most people have encountered the same problem and are just waiting for the creators of Confluence to add this feature, but this issue has been dragging on since 2011!

Is there a JavaScript code to stop a webpage from detecting you have clicked off the tab?

I am given a challenge to write a JavaScript code that stops a webpage from detecting you have clicked off the tab. I have to inject JavaScript in the webpage via Chrome extension, but the webpage pauses the execution of any JavaScript when you switch tabs or applications. Trivial solutions such as sending continous messages to the webpage does not work.

The only hint I am given is that this can be done in a few lines of code. Rules:

There are only two rules. 1) No DOM manipulation allowed such as overriding document.visibilityState. 2) You can only change the code in one file: background.js. When testing your code, we will use the original challenge code and only add in your updated background.js file.

How can this be accomplished?

I am only allowed to modify a file called background.js:
console.log("background.js running");

Here is the code inside a file called contentScript.js (I cannot modify this file):

function start() {
    // This function is called when the extension is now running on the webpage
    console.log("contentScript.js started")

    // Initialize list to contain logged timestamps
    let loggedTimestamps = [new Date()]

    // Get output list element
    const outputList = document.getElementById("output-stream-list")

    // Get status element
    const statusElement = document.getElementById("status")

    const log = () => {
        // Grab the current visibility state
        const visibilityState = document.visibilityState
        const isTabActive = visibilityState === 'visible'
        if (!isTabActive) {
            // Tab is not active, do not log
            return
        }

        // Get current local time 
        const now = new Date()

        // Set threshold for gap
        const threshold = 1400 // with error margin

        // Check if last timestamp was too long ago
        const lastDiff = now - loggedTimestamps[loggedTimestamps.length - 1]
        if (lastDiff > threshold) {
            // Create new list item and prepend to list
            const listItem = document.createElement("li")
            listItem.appendChild(document.createTextNode(`Tab not visible for ${lastDiff / 1000} seconds! :(`))
            outputList.prepend(listItem)
        }

        // Create new list item and prepend to list
        const logText = `${visibilityState} ${now.toLocaleTimeString()}`
        const listItem = document.createElement("li")
        listItem.appendChild(document.createTextNode(logText))
        outputList.prepend(listItem)

        // Log timestamp
        loggedTimestamps.push(now)

        // Determine if the logged timestamps have been continuous (ie. no gapps greater than threshold)
        let success = true
        for (let i = 1; i < loggedTimestamps.length; i++) {
            const diff = loggedTimestamps[i] - loggedTimestamps[i - 1]

            if (diff > threshold) {
                success = false
                break
            }
        }

        // Set status
        statusElement.innerText = success ? "Tab has always been active :)" : "Tab became inactive :("
        statusElement.style.color = success ? "green" : "red"
    }

    // Log every second
    setInterval(log, 1000)
}

start()

Tried sending messages on fixed intervals, messing with focus elements, etc.

OpenAPI Schema Validator for ReactJS

I’m attempting to create a ReactJS project (Vite) that takes an OpenAPI schema (in JSON or YAML format) as input. So, I need a library that can validate OpenAPI schema.

I searched for some similar libraries but couldn’t find any. Whenever I came across a library that does this type of thing it was built for the nodejs environment. So, can anyone help me and tell me if there is any way to validate my OpenAPI schema in my ReactJS project?

Capture chrome performance report programmatically with JavaScript?

We’ve been running a CPU intensive web application and there are some challenges debugging the performance issues as the hardware and CPU availability is different per user.

Although, we tried checking the performance profile and monitoring in a remote debug. We wanted to capture these information programmatically with JavaScript, when the application is running and log the information to analyse the problem more efficiently.

Does someone know an npm package which helps us capture the following information:

  • GPU information in chrome (Hardware acceleration is enabled or not).
  • CPU consumption on a specific tab.
  • JS heap size.
  • Long running tasks.

p.s. I’ve come through this npm package https://www.npmjs.com/package/lighthouse. But it doesn’t seem to support ES module format and also doesn’t provide some of the information I need in my performance metrics.

Appreciate some help here.

I get invalid token error when trying to verify id token with firebase

I am trying to pass a token from my react app to the flask server so I can verify it.

this is the flask route

@app.route("/tasks", methods=["GET"])
def get_tasks():
    try:
        id_token = request.headers.get("Authorization").split(" ")[1]
        print(id_token)
        # Verify the ID token while checking if the token is revoked by
        # passing check_revoked=True.
        decoded_token = auth.verify_id_token(id_token)
        print(decoded_token)
        # Token is valid and not revoked.
        uid = decoded_token['uid']
    except auth.RevokedIdTokenError as e:
        # Token revoked, inform the user to reauthenticate or signOut().
        return jsonify('RevokedIdTokenError')
    except auth.UserDisabledError as e:
        # Token belongs to a disabled user record.
        return jsonify('UserDisabledError')
    except auth.InvalidIdTokenError as e:
        # Token is invalid
        return jsonify('InvalidIdTokenError')

and this is the react part

async function getTaskName() {
    try {
      const userToken = await getToken()
      const response = await fetch('http://127.0.0.1:5000/tasks',{
        method : 'GET',
        headers: {
          'Authorization': `Bearer ${userToken}` // Include token in Authorization header
        }
      });
      const data = await response.json();
      console.log(data)
      //setTask(data)
    } catch (error) {
      console.error('Error fetching task:', error);
    }
  }

I checked if the userToken is type of string on both ends
I printed in the console both tokens and they are both identical
I printed the error from the exception, see it below, however my computer clock is set to automatic and it seems correct
Token used too early, 1711964786 < 1711964789. Check that your computer's clock is set correctly.

website content getting blur after downloaded [closed]

I have a created a website in that when we enter the details then we are going to get the certificate it is good in website view and in tablets but when it is in mobile view while displaying it is good but after downloading it’s getting blur how to fix it
`function downloadCertificateAsImage() {
// Use html2canvas to capture the content of the .certificate container
html2canvas(document.querySelector(‘.certificate’), {
// scale: 1, // Increase scale for higher resolution
onrendered: function (canvas) {
// Convert the canvas to a data URL representing the image
const imageData = canvas.toDataURL(‘image/jpeg’); // Adjust quality to 0.8

        // Create a temporary anchor element
        const downloadLink = document.createElement('a');
        downloadLink.href = imageData;
        downloadLink.download = 'certificate.jpg'; // Set the file name for download
        
        downloadLink.click(); // Simulate click to trigger download
    }
});

}`

i am facing the issue when submiting the form of second section , the returns back to the first section insted of updating the content of curent page

User
this is my script for the single page with side bar in which 4 four buttonsrespectivey for page 1 page 2 page 3 page 4, these four pages are in a single template and containing the relevant content , page is containg two form, the first form showing the drop down of the loc_ids as i selects the value from the drop down and submits the form it should update the current page content as the second form from the views file rendering the same template which containing the four pages , as the view sending the value to the template, on the front as page loading completes it showing me the first page which welcome page , instead of this how can i remain on the current page(specific section of the template), this is due to as the view rendering the template and on submiting the previus form it rediret to the second form’s view which is rendering the template and when loading it show the template from the start . on tis page i have a multiple forms , here i have also same forms but rendering from diffrent views.

<script>
  window.addEventListener('load', function() {
    var urlPath = window.location.pathname;

    if (urlPath === "{% url 'display_table' %}") {
      showPage('page1');
    } else if (urlPath === "{% url 'get_loc_id_for_table' %}") {
      showPage('page2');
    } else if (urlPath === "{% url 'get_loc_id' %}") {
      showPage('page3');
    }
  });

  var pages = document.querySelectorAll('.page');

  function showPage(pageId) {
    pages.forEach(function(page) {
      if (page.id === pageId) {
        page.classList.remove('hidden');
      } else {
        page.classList.add('hidden');
      }
    });
  }

  function submitForm(event, formId) {
    event.preventDefault(); // Prevent default form submission behavior
    var form = document.getElementById(formId);
    var formData = new FormData(form);

    // AJAX request to submit the form data
    var xhr = new XMLHttpRequest();
    xhr.open('POST', form.action);
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); // Add this line to identify the request as AJAX
    xhr.onload = function() {
      if (xhr.status === 200) {
        // Update the page content with the received HTML
        document.getElementById('selected-tables').innerHTML = xhr.responseText;
      } else {
        // Handle errors if needed
      }
    };
    xhr.send(formData);
  }
</script>

here is my page 2 conent also as i am submiting the first drop down form instead of updating the contebt section(page2), it go back to the welcome page,

<div id="page2" class="page hidden">

<form id="loc_id_form" method="post" action="{% url 'get_db_by_loc_id_for_table' %}" onsubmit="submitForm(event, 'loc_id_form', 'selected-tables');">
        {% csrf_token %}
        <label for="loc_id"></label>
        <select name="loc_ids_t1" id="loc_id" style="width: 150px;">
            {% for loc_ids in dis_loc_id %}
                <option value="{{ loc_ids }}">{{ loc_ids }}</option>
            {% endfor %}
        </select>
        <button type="submit">Submit</button>
    </form>
    
    
    {% comment %} ...........second form .................. {% endcomment %}
    
        
    <form id="select-table-form" method="post" action="{% url 'save_selected_tables_tables' %}"  >
            {% csrf_token %}
            <div class="container">
                <!-- Left partition for available tables -->
                <div class="partition left-partition">
                    <h3></h3>
                    <select id="available_tables" size="12" multiple>
                        {% for tables_all in tables %}
                            <option value="{{ table }}">{{ table }}</option>
                        {% endfor %}
                    </select>
                </div>
    
                    <input type="hidden" name="selected_loc_id" value="{{ selected_loc_id }}">
                    <input type="hidden" name="db_name" value="{{ db_name }}">
                    <input type="hidden" name="accounting_system" value="{{ accounting_system }}">
                    <input type="hidden" name="ip" value="{{ ip }}">
                    <input type="hidden" name="port" value="{{ port }}">
                    <input type="hidden" name="source_table_name" value="{{ source_table_name }}">
                    {% for table in tables %}
                    <input type="hidden" name="available_tables" value="{{ table }}">
                    {% endfor %}
    
                <!-- Arrow buttons for moving options -->
                <div class="toggle-arrows">
                    <button id="move-to-right" type="button">→</button>
                    <button id="move-to-left" type="button">←</button>
                </div>
    
                <!-- Right partition for selected tables -->
                <div class="partition right-partition">
                    <h3></h3>
                    <select id="selected-tables" name="selected_table" size="12" multiple></select>
                </div>
            </div>
            
            <button id="submit-button" type="submit" style="display: none;">Submit</button>
        </form> 

    </div>`

Uncaught runtime errors: Infinite redirect in navigation guard

I have a vue3 router defined with the following routes

export const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    name: "浏览题目",
    component: HomeView,
    meta: {
      access: "canAdmin",
    },
  },
  {
    path: "/noAuth",
    name: "无权限",
    component: NoAuthView,
    meta: {
      access: "canAdmin",
    },
  },

  {
    path: "/admin",
    name: "管理员可见",
    component: AdminView,
    meta: {
      access: "canAdmin",
    },
  },
  {
    path: "/about",
    name: "关于我的",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "../views/AboutView.vue"),
  },

To implement a simple permission management function, determine whether the user has access permission based on the routing information of the page accessed by the user. If so, it will jump to the original page, otherwise it will be intercepted.

<script setup lang="ts">
import BasicLayout from "@/layouts/BasicLayout.vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";

const router = useRouter();
const store = useStore();
router.beforeEach((to, from, next) => {
  if (to.meta?.access === "canAdmin") {
    if (store.state.user.loginUser?.role !== "admin") {
      next("/noAuth");
      return;
    }
  }
  next();
});
</script>

Why do I get an error when I click to jump to another page after refreshing?

Using aliases in javascript files using tsconfig

I have a project that was created using Create React App, in this project the development is in javascript, but I want to use typescript in some places, initially I had jsconfig, which had aliases written with which I could write convenient imports, but when I added tsconfig they started to conflict and I deleted jsconfig, but for javascript files typescript aliases do not work, is there a solution for this situation so that I can use alias in both javascript files and typescript files?

tsconfig

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    }
  },
  "include": ["src", "./declaration.d.ts"]
}

I tried to combine js config and ts config, but I got an error, I also tried to use just tsconfig, but it doesn’t work for js files

Issues with centering a modal overlay on mobile screens

I am working on a website with the structure as shown in this codepen. Modal-test . In codepen, there doesn’t seem to be any issue when i open the Chrome devtools and toggle device toolbar to see how the website will function on mobile screens but if i open it as a local html page (with CSS and JS linked), the modal is not centered on the screen in that mode. Same issue with Firefox (however I noticed that as long I turn the touch simulation off in firefox, the modal is centered, turning it on un-centers it.)

function showModal() {
    if (modalVisible) return;

    modalVisible = true;
    modal.style.display = "flex";
    document.body.appendChild(modal);
  }

I have tried to figure out how to center the modal on the screen while also not scrolling away from the content underneath it but I just can’t find the problem.

fix Prototype_Pollution error from checkmarx

the word ‘substring(1)’ in line window.location.search.substring(1) get error Prototype_Pollution,
Assigning external properties without validation may allow object properties pollution and affect application’s normal behavior.
how fix this code?

var QueryString = function () {
// This function is anonymous, is executed immediately and 
// the return value is assigned to QueryString!
var query_string = {};

const allowed = new Set([
    'rqid',
    'rowId',
    'sid',
    'RequestId',
    'RequestTypeID',
    'mode',
    'id',
    'requestIdList',
]);

var query = DOMPurify.sanitize(window.location.search.substring(1));
var vars = query.split("&");

for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");

    // If first entry with this name
    if (typeof query_string[pair[0]] === "undefined") {
        if (allowed.has(pair[0])) {
            query_string[pair[0]] = decodeURIComponent(pair[1]);
        }
        // If second entry with this name
    } else if (typeof query_string[pair[0]] === "string") {
        if (allowed.has(pair[0])) {
            var arr = [query_string[pair[0]], decodeURIComponent(pair[1])];
            query_string[pair[0]] = arr;
        }
        // If third or later entry with this name
    } else {
        if (allowed.has(pair[0])) {
            query_string[pair[0]].push(decodeURIComponent(pair[1]));

        }
    }
}

return query_string;

}();

how should the pictures in the article be uploaded?

I want to publish articles through this editor, how should the pictures in the article be uploaded?, 1. Upload to the server when the article is saved, 2. Upload when inserting it into the article, which method is more suitable, the second method If the picture is deleted after uploading, what should the user do with the previous step by going back?

I am now using the second method just mentioned, but I think there will be a trigger fallback and I have to re-upload it, which is not suitable for me.

Is it necessary to set `secure: true` when connecting to an https server?

I have a Nodejs backend that my frontend proxies to through Nginx, which is responsible for routing all traffic. I’m using Let’s Encrypt, and the server can be accessed by going to it (https://example.com). I also have load balancing setup to route traffic upstream via the ‘least connections’ protocol.

On the frontend, I connect socket.io like this:

import { io, ManagerOptions, SocketOptions } from 'socket.io-client';

const otherOpts = {};
const socket = io('https://example.com', {
    ...otherOpts,
    secure: false,
} as Partial<ManagerOptions & SocketOptions>);

This works as is, but in the current context, what would I need secure: true for? Is this the condition that determines ws vs wss? The client connects over https already, so is this something I can safely omit?