How to make a div the same width as the element above it WITHOUT using relative positioning?

I have a form where I am trying to set up a dropdown menu below an input field.

My issue is that I can’t get the dropdown menu to be the same width as the input field above it.

If I set the dropdown menu to use relative positioning and I set it to 75% (the same width as the input field) then it works. But the issue then becomes that the dropdown menu pushes down the elements below it when it expands and that is not what I want. I want it to overlay the elements below it when it expands.

So when I set the dropdown div to use relative positioning the width is ok but then it pushes down the elements which is what I dont want. But then when I set it to use fixed positioning it overlays the elements below it ( which is what I want ) but then I cannot get it to have the same width as the input above it.

How do I make this dropdown div BOTH overlay the elements below it when it extends and ALSO be the same exact width as the input field above it?

Ty for your time and God Bless.

here is a reference to the dropdown div and the input field above it

const input = document.getElementById("bizcategory");
const listContainer = document.getElementById("myList");


const words = ['option5', 'option6', 'option7', 'option8',
  'option9', 'option10', 'option11'
];

for (let i = 0; i < words.length; i++) {
  const newItem = document.createElement("li");
  newItem.textContent = words[i];
  newItem.style.listStyle = "none";
  listContainer.appendChild(newItem);

}



const listItems = listContainer.querySelectorAll("li");

input.addEventListener("focus", () => {
  listContainer.style.display = "block";
})

input.addEventListener("blur", () => {
  setTimeout(() => {
    listContainer.style.display = "none";
  }, 200);
});

listItems.forEach(i => i.addEventListener("click", function() {
  input.value = i.textContent;
  listContainer.style.display = "none";
}));
.signininput {
  height: 40px;
  width: 75%;
  box-sizing: border-box;
}


.list-container {
  display: none;
  border: 1px solid #ccc;
  background-color: white;
  width: 75%;
}

.list-container ul {
  list-style: none;
  padding: 0;
  margin: 0;
  width: 75%;
}

.list-container li {
  padding: 5px;
}

.list-container li:hover {
  background-color: #f0f0f0;
  cursor: pointer;
}
<input class="signininput"  type="text" id="bizcategory" name="bizcategory" placeholder="" maxlength="255" onblur="this.value=removeSpaces(this.value);"></input>
<div class="list-container" id="myList">
  <ul style="list-style: none;">
    <li>Option 1</li>
    <li>Option 2</li>
    <li>Option 3</li>
    <li>Option 4</li>
  </ul>
</div>

In Hyperledger fabric when i query qscc ‘GetBlockByTxID’ i get an error saying” error no such transaction ID in index”

I am trying to get the block number and the block hash on Hyperledger fabric network from my channel, but i was able to get the details using cli with the same transaction ID, when i try with the latest fabric-gateway i get the following error

cause: Error: 2 UNKNOWN: evaluate call to endorser returned error: chaincode response 500, Failed to get block for txID "95841fc8ba7c49bf333430e0fd9ed052a97eb9910610bfd22faa05802c2d2cc5"
  , error no such transaction ID ["95841fc8ba7c49bf333430e0fd9ed052a97eb9910610bfd22faa05802c2d2cc5"
  ] in index

The exact version of gateway are

"@hyperledger/fabric-gateway": "^1.7.1",
"@hyperledger/fabric-protos": "^0.2.2",

The below code works for cli

peer chaincode query -C mychannel -n qscc -c '{"Args":["GetBlockByTxID","mychannel","95841fc8ba7c49bf333430e0fd9ed052a97eb9910610bfd22faa05802c2d2cc5"]}'

Iam using the fabric sample network and modifying the asset transfer basic gateway code.

app.get("/getBlockByTxId/:txId", async (req, res) => {
  try {
    const { txId } = req.params;
    
    const network = gateway.getNetwork(channelName);
    const contract = network.getContract("qscc");
    // Use `GetBlockByTxID` to fetch the block containing the transaction
    console.log("NETWORKKK", network.getName());
    console.log(
      "Methods:",
      Object.getOwnPropertyNames(Object.getPrototypeOf(network))
    );

    const result = await contract.evaluateTransaction(
      "GetBlockByTxID",
      network.getName(),
      txId
    );

    // Parse the result as a block
    const block = Block.decode(result); // Decoding block using Hyperledger protobuf
    res.send(block);
  } catch (error) {
    console.error("Error in getBlockByTxId:", error);
    res.status(500).send("Failed to fetch block by transaction ID");
  }
});

how to require a function from another file inside of the code gen for ajv standalone code?

ajv.addKeyword("isValidString", {
  type: "string",
  code(cxt) {
    const { data, schema, gen } = cxt;

    gen.func(
      "isValid",
      ["data"],
      `
      const external_func = require("./customValidation.js");
      return external_func(data);
    `
    );

    cxt.fail(`!isValid(data)`);
  },
});

So the above sums up the intent.

The key is this line:

const external_func = require("./customValidation.js");

But the code above doesn’t work.

This is the code it generated:

function validate10(
  data,
  { instancePath = "", parentData, parentDataProperty, rootData = data } = {}
) {
  let vErrors = null;
  let errors = 0;
  if (errors === 0) {
    if (data && typeof data == "object" && !Array.isArray(data)) {
      let missing0;
      if (data.username === undefined && (missing0 = "username")) {
        validate10.errors = [
          {
            instancePath,
            schemaPath: "#/required",
            keyword: "required",
            params: { missingProperty: missing0 },
            message: "must have required property '" + missing0 + "'",
          },
        ];
        return false;
      } else {
        if (data.username !== undefined) {
          const _errs1 = errors;
          if (errors === _errs1) {
            if (typeof data.username === "string") {
              async function isValid(data) {
                if (!isValid(data)) {
                  validate10.errors = [
                    {
                      instancePath: instancePath + "/username",
                      schemaPath: "#/properties/username/isValidString",
                      keyword: "isValidString",
                      params: {},
                      message: 'must pass "isValidString" keyword validation',
                    },
                  ];
                  return false;
                }
              }
            } else {
              validate10.errors = [
                {
                  instancePath: instancePath + "/username",
                  schemaPath: "#/properties/username/type",
                  keyword: "type",
                  params: { type: "string" },
                  message: "must be string",
                },
              ];
              return false;
            }
          }
        }
      }
    } else {
      validate10.errors = [
        {
          instancePath,
          schemaPath: "#/type",
          keyword: "type",
          params: { type: "object" },
          message: "must be object",
        },
      ];
      return false;
    }
  }
  validate10.errors = vErrors;
  return errors === 0;
}

In particular, this makes no sense:

              async function isValid(data) {
                if (!isValid(data)) {
                  validate10.errors = [
                    {
                      instancePath: instancePath + "/username",
                      schemaPath: "#/properties/username/isValidString",
                      keyword: "isValidString",
                      params: {},
                      message: 'must pass "isValidString" keyword validation',
                    },
                  ];
                  return false;
                }
              }

change value of element attributes to that of another attribute

I want the value of attribute ‘data-bs-content’ in all elements to be set to the value found in the ‘data-my-data’ attribute when the document is loaded.

I’ve tried about a dozen different strategies that I could think of, but none seem to be working.

The reason I don’t just put the value in ‘data-bs-content’ is because there will be processing that happens on the data in ‘data-my-data’ before setting the value.

<!doctype html>
<html>

<head>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-0pUGZvbkm6XF6gxjEnlmuGrJXVbNuzT9qBBavbLwCsOGabYfZo0T0to5eqruptLy" crossorigin="anonymous"></script>

    <script>
        $(document).ready(function() {

          var popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
          var popoverList = popoverTriggerList.map(function(popoverTriggerEl) {
            var popover = new bootstrap.Popover(popoverTriggerEl, {
              container: 'body',
              trigger: 'click'
            });
            return popover;
          });

          var $element = $('[data-bs-content]');
          $element.attr( "data-bs-content" , function(index, currentValue) {
            return $(this).getAttribute('data-my-data');
          });

        });
    </script>

</head>

<body>
<br/>
<a href="#"
   data-bs-toggle="popover"
   data-bs-content="default data"
   data-my-data="my data 1"
>
    CLICK ME 1
</a>
<br/>
<br/>
<a href="#"
   data-bs-toggle="popover"
   data-bs-content="default data"
   data-my-data="my data 2"
>
    CLICK ME 2
</a>

</body>
</html>

The dataset component does not configure the legend

I’m configuring two charts and the legend only appears when I use series.data, but it doesn’t appear when I use the dataset component (series.datasetIndex and series.encode). Nothing I tried worked. Here’s the code:

   document.addEventListener("DOMContentLoaded", () => {

        // sytem
        const chartSystem = () => {
            return {
                "source": {
                    "first": [
                        ["name", "value"],
                        ["Pressure", 40],
                        ["Temperature", 64],
                        ["Atmosphere", 89]
                    ],
                    "second": [
                        ["name", "value"],
                        ["Label 1", 15],
                        ["Label 2", 68]
                    ]
                }
            }
        }

        // send
        const pullDataset = [];
        const pullData = [];

        const chartSend = () => {
            const { first, second } = chartSystem().source;

            pullDataset.push({
                source: first
                // sourceHeader: true
            });

            pullData.push(
                {
                    data: second.slice(1).map(([name, value]) => ({
                        name,
                        value
                    }))
                }
            );
        };

        chartSend();

        // frames
        const chartUse = echarts.init(document.getElementsByClassName("chart")[0]);

        function chartFrameSwitch0 () {

            const tooltip0 = {
                show: true
            };
            
            const useDataLegend = pullDataset[0].source.slice(1).map(item => item[0]);
            console.log(useDataLegend);

            // legend
            const legend0 = [
                {
                    show: true,
                    data: useDataLegend,
                    borderWidth: 2,
                    borderColor: 'red'
                },
                {
                    show: true,
                    data: pullData[0].data.map(item => item.name),
                    borderWidth: 2,
                    borderColor: 'blue',
                    left: 'center',
                    top: '5%'
                }
            ];

            const grid0 = [
                {
                    top: '30%',
                    left: '5%',
                    width: '38%',
                    height:'30%'
                }
            ];

            const xAxis0 = [
                {
                    gridIndex: 0,
                    type: 'category'
                }
            ];

            const yAxis0 = [
                {
                    gridIndex: 0,
                    type: 'value'
                }
            ];

            const series0 = [
                {
                    type: 'bar',
                    color: ['#49a6de', '#ff7500', '#ff00ff'],
                    colorBy: 'data',
                    datasetIndex: 0,
                    encode: {
                        x: 0,
                        y: 1
                    },
                    xAxisIndex: 0,
                    yAxisIndex: 0
                },
                {
                    type: 'pie',
                    legendIndex: 0,
                    center: ['70%', '50%'],
                    data: pullData[0].data
                }
            ];

            const option = {
                dataset: [pullDataset[0]],
                legend: legend0, // Keep both legends in the array
                tooltip: tooltip0,
                grid: grid0,
                xAxis: xAxis0,
                yAxis: yAxis0,
                series: series0
            };

            chartUse.setOption(option);
        }

        chartFrameSwitch0();

    })
<head>
    <script src='https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js'></script>
</head>
    
<div class='chart' style='width: 100%; height: 100vh;'></div>

See the console.log of useDataLegend:

[
  "Pressure",
  "Temperature",
  "Atmosphere"
]

This is a manual way I tried to set legend.data: [...]. I tried using series.encode, but it doesn’t seem to support setting the legend.

D3. How to scale the text so that it all fits into the drawing area

I use D3 to draw everything on the screen, the problem is that i want all the elements to fit in the block, while leaving as little free space as possible, how to do this, size can take a value from 1 to infinity. At the same time, it is necessary to preserve their ratio between themselves, how to do this is clear, but the question is how to calculate the multiplier that will allow them all to fit into the given block sizes.

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.16.0/d3.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/d3-cloud/build/d3.layout.cloud.min.js"></script>
const width = 800;
const height = 600;

const svg = d3
    .select("#tagCloud")
    .append("svg")
    .attr("width", width)
    .attr("height", height);

const layout = d3.layout.cloud()
    .size([width, height])
    .words(tags.map(tag => ({ text: tag.text, size: tag.size, url: tag.url })))
    .padding(5)
    .rotate(() => ~~(Math.random() * 2) * 90)
    .font("Impact")
    .fontSize(x => x.size)
    .on("end", draw);

layout.start();

function draw(words) {
    svg.append("g")
        .attr("transform", `translate(${width / 2}, ${height / 2})`)
        .selectAll("text")
        .data(words)
        .enter()
        .append("text")
        .style("font-size", x => `${x.size}px`)
        .style("font-family", "Impact")
        .style("fill", () => d3.schemeCategory10[Math.floor(Math.random() * 10)])
        .attr("text-anchor", "middle")
        .attr("transform", x => `translate(${x.x}, ${x.y}) rotate(${x.rotate})`)
        .text(x => x.text)
        .on("click", function (item, index) {
            if (item.url) {
                window.location.href = item.url;
            }
        });
}

AuthMiddleware Deprecated: How to Fix Issues with clerkMiddleware?

With the deprecation of authMiddleware, I’m looking for guidance on how to update my code. My previous implementation was structured like this:The code
What would be the recommended approach to achieve the same functionality with the updated tools or methods provided by Clerk? Any examples or best practices would be greatly appreciated!

I tried going through the documentation. But being a beginner I couldn’t get much out of it. Then I tried some alternatives using the help of chatGPT. Those too were unsuccessful.

The code is here:

`import { authMiddleware } from '@clerk/nextjs'

export default authMiddleware({
publicRoutes: "/site","/apit/"
})
export const config = {
matcher: ['/((?!. +\. [\w] +$ |_next).*)', '/',
'/(api|trpc) (.*)'],
}`

How to pass a long user token from React Native to a React web app?

I’m building a React Native app that includes a button to redirect the user to a React-based web app. The goal is to pass the userToken from the mobile app to the web app so the user can remain authenticated. My initial idea was to include the token as a query parameter in the URL, like this:

const handleStatisticsClick = async () => {
   WebBrowser.openBrowserAsync(
     https://www.MY-URL.COM/user-profile/creator-hub?accessToken=${userToken.replace(/./g,'-')}
  ); };

How can I securely and reliably pass a very long userToken from my React Native app to my React web app? Are there better alternatives to using a query parameter for this purpose?
However, the token is quite large (several thousand characters), and I’m concerned about potential issues with URL length limits or other limitations when passing such a large token in the query string. For example, when testing this implementation, the browser occasionally fails to open the URL properly, and some services seem to truncate the query parameters. Additionally, I am not sure how the receiving server handles URLs with very large query strings. If relevant, the server is configured to accept standard-length query strings but may require adjustments for such edge cases.

Furthermore, I’m worried about the security of passing such sensitive information through the URL.

Debugging Attempts

Using URL Parameters: I initially attempted to pass the token in the URL query string, but encountered issues with length limits and concerns about sensitive data exposure.

Alternative Shortened Token: I considered generating a short-lived unique identifier in the mobile app that the web app could exchange for the actual token via an API call, but this adds complexity and might introduce latency.

Using Cookies: I explored the possibility of setting cookies, but I am unsure how to share cookies securely between a mobile app and a web app.

Question

Has anyone encountered this issue before? What solutions have worked for you? I’m looking for best practices to ensure reliability and security.

I tried passing the userToken directly as a query parameter in the URL using the WebBrowser.openBrowserAsync function in React Native. I expected the token to be transferred seamlessly to the web app and allow the user to stay authenticated.

However, I encountered concerns about potential URL length limits and security issues with including such a long token (several thousand characters) in the query string. Additionally, I’m worried about how this might affect different browsers or platforms.

I’m looking for a reliable and secure alternative to pass this token without running into these issues.

structure of AJV standalone code generation code formats

https://ajv.js.org/standalone.html#configuration-and-limitations

In the following given example of the link above:

import myFormats from "./my-formats"
import Ajv, {_} from "ajv"

const ajv = new Ajv({
  formats: myFormats,
  code: {
    source: true,
    formats: _`require("./my-formats")`,
  },
})

If you only use formats from [ajv-formats](https://github.com/ajv-validator/ajv-formats) this option will be set by this package automatically.

There is no further details on how the “./my-formats” file must be structured.

Can someone link to official documentation that explains how the "./my-formats" must be structured?

Best approach for creating an accessible multi-step form with aria-live step indicator?

I’m working on a multi-step form where each step is dynamically displayed using <template> elements. As the user progresses, the previous step is hidden, and the next step is revealed (with JavaScript).

For accessibility, I’ve added aria-live="polite" to the root of the HTML document, and I dynamically update the content based on the selected step using JavaScript.

My question is: which approach is more accessible?

  • Adding aria-live="polite" to the root element and updating it with JavaScript when the step changes.

OR

  • Adding aria-live="polite" to each <template> element, with the step title already included inside the template.

Ffmpeg Wasm Vanilla Won’t Load

I’ve build a simple script to load ffmpegwasm using vanilla JS but even though it’s simple I can’t get it to load. This is the code:

<script src="https://cdn.jsdelivr.net/npm/@ffmpeg/[email protected]/dist/umd/ffmpeg.min.js"></script> 
<p id="message">Press the button to load FFmpeg</p>
<button id="load-ffmpeg">Load FFmpeg</button>

<script>
    // Create FFmpeg instance
    const { FFmpeg } = FFmpeg;
    const ffmpeg = FFmpeg.createFFmpeg({ log: true });

    // Button click to load FFmpeg
    const button = document.getElementById('load-ffmpeg');
    const message = document.getElementById('message');

    button.addEventListener('click', async () => {
        message.textContent = 'Loading FFmpeg...';

        try {
            await ffmpeg.load();
            message.textContent = 'FFmpeg loaded successfully!';
        } catch (error) {
            message.textContent = 'Failed to load FFmpeg.';
        }
    });
</script>

Can you please help me understand where I have gone wrong.

Submitting a text in a HTML form with more than 1 space

Question at the end!

After years of HTML forms submissions, I realized this for the first time.
Suppose you have an input text in a form, and you type and submit:

There are  2 spaces before the number 2

If the form method=get, it will pass

There+are+2+spaces+before+the+number+2

in the URL, while if the form method=post, it will pass

There are 2 spaces before the number 2

meaning with a single space.

Now, I understand I could use encodeURIElement or whatever, I can JSON it, I can invent a totally new encoding style, base97 for the matter.
But this is just insane! If you REMOVE a space, you LOSE information, it’s not a 1:1 transformation and you will never be able to go back.
I discovered it “by chance” because I was using the string to do a MySQL search with LIKE %whatever% and it was always giving me back 0 elements found (and yes, I am using prepared statements).
This is my question: what is the advantage of NOT ENCODING MULTIPLE SPACES?! I do not see ANY advantage, but if the HTML specifications have been written like this, I hope there is a VALID reason. If the form submits values encoded in a way that is not reversible, then you can NEVER trust it.

Unable to share stream between two users with PeerJS

I am trying to create something where one user shares their stream and other watches the shared stream. I have created basic sharer and viewer.html files and used PeerJS for connection and video sharing.

The issue i am facing is i am unable to view the stream.

Here is my code

sharer.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Screen - Sharer</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link rel="shortcut icon" href="chat.png" type="image/x-icon">
  <script src="https://unpkg.com/[email protected]/dist/peerjs.min.js"></script>
  <style>
    * {
      font-family: 'Jetbrains Mono';
    }
  </style>
</head>

<body class="h-screen bg-green-400 flex justify-center items-center">
  <div class="flex gap-2 flex-col bg-white border-2 border-black p-2 justify-center items-center">
    <h1 class="text-xl font-bold">Share Screen</h1>
    <div class="flex justify-center items-center gap-3">
      <p class="text-sm">Your ID: <span id="your-id"></span></p>
      <button id="share" class="p-1 px-2 text-sm border-2 border-black bg-yellow-200">Share</button>
    </div>
    <div class="mt-4">
      <video id="video" class="h-[400px] w-[700px]" autoplay controls></video>
    </div>
  </div>
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      let stream;
      const btn = document.getElementById('share');
      const video = document.getElementById('video');

      // Initialize PeerJS
      const peer = new Peer('aditya'); // Use a unique ID for this peer

      peer.on('open', id => {
        document.getElementById('your-id').textContent = id;
        console.log('Peer connected with ID:', id);
      });

      btn.addEventListener('click', () => {
        navigator.mediaDevices.getDisplayMedia({ video: true, audio: true })
          .then(mediaStream => {
            stream = mediaStream;
            video.srcObject = stream;

            // Play the video locally
            video.addEventListener('loadedmetadata', () => {
              video.play();
            });

            // Wait for a viewer to connect
            peer.on('call', call => {
              console.log('Viewer is calling...');
              call.answer(stream); // Send the stream to the viewer
            });
          })
          .catch(err => {
            console.error('Error sharing screen:', err);
          });
      });

      peer.on('error', err => {
        console.error('PeerJS Error:', err);
      });
    });
  </script>
</body>

</html>

this is viewer.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Screen - Viewer</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link rel="shortcut icon" href="chat.png" type="image/x-icon">
  <script src="https://unpkg.com/[email protected]/dist/peerjs.min.js"></script>
  <style>
    * {
      font-family: 'Jetbrains Mono';
    }
  </style>
</head>

<body class="h-screen bg-green-400 flex justify-center items-center">
  <div class="flex gap-2 flex-col bg-white border-2 border-black p-2 justify-center items-center">
    <h1 class="text-xl font-bold">Screen Viewer</h1>
    <div class="flex justify-center items-center gap-3">
      <p class="text-sm">Your ID: <span id="your-id"></span></p>
      <button id="connect" class="p-1 px-2 text-sm border-2 border-black bg-yellow-200">Connect</button>
    </div>
    <div class="mt-4">
      <video id="video" class="h-[400px] w-[700px]" autoplay controls></video>
    </div>
  </div>
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      const btn = document.getElementById('connect');
      const video = document.getElementById('video');

      // Initialize PeerJS
      const peer = new Peer('agrima'); // Use a unique ID for this peer

      peer.on('open', id => {
        document.getElementById('your-id').textContent = id;
        console.log('Peer connected with ID:', id);
      });

      btn.addEventListener('click', () => {
        console.log('Attempting to call "aditya"...');

        // Call the sharer (aditya)
        const call = peer.call('aditya');

        if (call) {
          // Receive the stream
          call.on('stream', remoteStream => {
            console.log('Stream received:', remoteStream);
            video.srcObject = remoteStream;
            video.addEventListener('loadedmetadata', () => {
              video.play();
            });
          });

          call.on('error', err => {
            console.error('Call error:', err);
          });
        } else {
          console.error('Unable to connect to the sharing peer.');
        }
      });

      peer.on('error', err => {
        console.error('PeerJS Error:', err);
      });
    });
  </script>
</body>

</html>

any help is appreciated!

Detect page change with 2sxc app in Blazor/Oqtane

Since Blazor and Oqtane are SPA, content is added to the DOM with no actual load to be always detected.

Also, 2sxc still does not seem to work with Blazor / .net on the client browser.

This leaves quite a few usual cases like every “on page load” with no options for easy implementation.

So, resorting only to common razor server side code and plain javascript, how can I trigger a js function every time a page is shown, either for the first time or recurrent accesses with no forced reloads?

Let’s say a simple:

<script src="sayhello.js"></script>

and

function showalert(){
    alert("This is page ABC");
}
window.onload = showalert();

Error WebSocket connection to ‘ws://127.0.0.1:1430/__tauri_cli’ failed: WebSocket is closed due to suspension

I am making a Tauri app Github Repo .

So I have two pages clock.html and index.html . There is one event listener attached to an element in index.html . So when I redirect the user to clock.html, javascript complains about the element no longer existing (basically a TypeError) which possibly halts the execution of upcoming javascript code.
To fix that I added an if statement around the addEventListener call to only add the event listener if it was on the correct page . But on doing that I get this weird error (title) which has no explanation whatsoever in the context of a Tauri app.

main.js ( /frontend/src/main.js )

async function addAlarm(targetDate) {
   const alarm = {
      date: targetDate.toString()
   }
   const response = await fetch("http://localhost:6969/alarms/" + userID + '/',
      {
         method: "POST",
         headers: {
            "Content-Type": "application/json"
         },
         body: JSON.stringify(alarm)
      }

   );
   let t = await response.text();
   console.log(t);
   document.getElementById('alarms').insertAdjacentHTML('afterbegin', `<div> ${t}</div>`);
}

async function register() {

   const data = {
      name: document.querySelector('[name="usercode"]').value,
      serverpass: document.querySelector('[name="server-password"]').value
   }
   const response = await fetch('http://localhost:6969/users', {
      method: 'POST',
      headers: {
         "Content-Type": "application/json"
      },
      body: JSON.stringify(data)
   });
   userID = await response.text();
   return userID;
}
if (window.location.href === "/") {
   document.getElementById("login").addEventListener("click", async event => {
      event.preventDefault();
      await register();
      window.location.replace("/clock");
   });
}
if (window.location.href === "/clock") {
   document.getElementById('add-alarm').addEventListener('click', async () => {
      await addAlarm(document.querySelector('[type="datetime-local"]').value);
   })
}