Firefox popup extension access localstorage of host page

I’m making an extension to automate a dozen API calls to a website I frequently use (Brightspace) so that I can quickly summary a lot of information very quickly. For security reasons and given how hacky it is so far, this extension WILL NOT be shared with others.

In the host page. I can easily access my JWT and from there I can craft all the necessary requests with fetch, parse, and organize the information how I want. (JSON.parse(localStorage["D2L.Fetch.Tokens"])["*:*:*"].access_token)

The problem is I’m now trying to move this code to a Firefox popup extension and I cannot find any way to access the host page localStorage directly. The only way I found is to make a content_scripts script that reads my JWT then saves it in browser.storage.sync so that my popup extension can then read it from there.

Is there a clean and direct way for popup extensions to read the host page localStorage?

Set HTML with style in a GrapesJs component

I use GrapesJs and I want to update the html content of a component.
So I use the components method of a component : cmp.components('<h1 style="text-align:left">Hello</h1>').
But when I retrieve the html content of my component (cmp.toHTML()) the style is not here.

How to sanitize request url in Next Js to prevent XSS attacks

We ran security vulnerability scan on our next js app.It detected XSS with following result

GET /../"> HTTP/1.0
Host:xxx.xxx.xx.x:3000

HTTP/1.1 308 Permanent Redirect
location: /../">/
Refresh: 0;url=/../">/
Date: TUE, 30 Jan 2024 02:36:50 GMT
Connection: close
/../">/

To mitigate this vulnerability, it suggested to sanitize request url.
As per my understanding the issue is with hiting url with script characters E.g. http://localhost:3000/../">
Is my understanding correct and how we can mitigate it?

CKeditor5 – The cursor does not move to the correct location after a click

I downloaded the zip package from the official CKEditor 5 page and implemented it by importing the ckeditor.js file. I am facing issues while editing the content.
And it happens that I need to click many times on the spot where I want to edit; if I click only once or twice, it doesn’t select any location.
video example

version ckeditor5-build-classic-41.0.0,
the instance of CKEditor does not have third-party plugins installed.

The issue occurs on an Ubuntu OS using the Google Chrome browser, but it works correctly in the Firefox browser. That’s why I am confused about the real problem.

I see the issue #11864 that apparently solved the problem, but it didn’t work even though it has been fixed for more than a year.

my javascript function couldn’t worl with input and label

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>

    <h3 style="position:absolute;top:15%">
        <i class="fa-face-smile"></i>
        Upload your FeedBack form for us!!
    </h3>
    <div class="form-box">
        <div class="textup">

            It only takes two minutes!!
        </div>
        <br />
        <form name="myForm" onsubmit="return( feedback());">
            <label for="uname">

                Name
            </label>
            <input type="text" id="uname"
                   name="uname" required>

            <label for="email">
                <i class="fa fa-solid fa-envelope"></i>
                Email Address
            </label>
            <input type="email" id="email"
                   name="email" required>

            <label for="phone">
                <i class="fa-solid fa-phone"></i>
                Phone No
            </label>
            <input type="tel" id="phone"
                   name="phone" required>

            <label>
                <i class="fa-solid fa-face-smile"></i>
                Do you satisfy with our service?
            </label>
            <div class="radio-group">
                <input type="radio" id="yes"
                       name="satisfy" value="yes" checked>
                <label for="yes">Yes</label>

                <input type="radio" id="no"
                       name="satisfy" value="no">
                <label for="no">No</label>
            </div>

            <label for="msg">
                <i class="fa-solid fa-comments"
                   style="margin-right: 3px;"></i>
                Write your Suggestions:
            </label>
            <textarea id="msg" name="msg"
                      rows="4" cols="10" required> 
            </textarea>
            <button type="submit">
                Submit
            </button>
        </form>
    </div>
    <div class="logoposition">
        <img src="images/WhatsApp Image 2024-01-27 at 12.37.00_0f8d14e3.jpg" class="logo" />
    </div>


    <style>

        body {
            margin: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-direction: column;
            height: 100vh;
            background-color: #bde5d2;
            font-family: 'Poppins', sans-serif;
            background-repeat: no-repeat;
            background-image: url('images/dodgeball-player-painted-vector.jpg');
            padding: 0;
            background-size: cover;
            background-position: center;
        }

        .textup {
            text-align: center;
            color: rgb(11, 118, 11);
            font-weight: 700;
        }

        i {
            margin-right: 3px;
        }




        .form-box {
            background-color: #fff;
            box-shadow: 0 0 10px rgba(36, 67, 40, 0.8);
            padding: 15px;
            border-radius: 8px;
            width: 500px;
            margin: 0 auto; /* Center the form horizontally */
            margin-top: 10%; /* Adjust the top margin as needed */
            opacity: 0.7;
        }


        form {
            max-width: 400px;
            margin: 0 auto;
        }

        .radio-group {
            display: flex;
            margin-bottom: 16px;
        }

        input[type="radio"] {
            margin-left: 8px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-size: 17px;
            color: green;
            font-weight: 600;
        }

        input,
        textarea {
            width: 100%;
            padding: 8px;
            margin-bottom: 12px;
            box-sizing: border-box;
            border-radius: 10px;
        }

        button {
            background-color: #368b44;
            color: #fff;
            padding: 10px;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            width: 100%;
            font-size: 15px;
            transition: .2s linear;
            opacity: 1 !important;
        }

            button:hover {
                background-color: #0a6808;
                border: none;
                transform: translateY(-10px);
                opacity: 1 !important;
            }

        .rounded {
            flex: none;
            width: 60px;
            height: 60px;
            border-radius: 50%;
            object-fit: cover;
        }

        .logo {
            object-fit: cover;
            display: block;
            /* Make sure the image fills the container width */

            max-height: 200px;
            min-height: 200px;
            max-width: 200px;
            border-radius: 50%;
            overflow: hidden;
            flex: none;
            width: auto;
        }

        .logoposition {
            right: 20px;
            position: absolute;
            top: 35px;
        }
    </style>

    <script>
        function feedback() {
            //check for empty input
            if (document.myForm.uname.value == "") {
                alert("Please fill in your name.");
                document.myForm.uname.focus();
                return false;
            }

            if (document.myForm.email.value == "") {

                alert("Please provide your password within 8 to 16 characters.");
                document.myForm.email.focus();
                return false;
            }

            if (document.myForm.yes.checked == false)
                if (document.myForm.no.checked == false) {
                    alert("Please select your gender.");
                    return false;
                } else if (document.myForm.yes.checked == true)
                    if (document.myForm.no.checked == true) {
                        return false;
                    }

            if (document.myForm.channel.value == "") {
                alert("Please select from where you hear about us!");
                document.myForm.channel.focus();
                return false;
            }

            return (true);
        }
    </script>
</body>
</html>

i expect that the alert will pop up. But it does not work and it seems like the function can’t call out. Other than that, the logo can be displayed fully. it shows that there still have some side cant display.I put it into a <div> box and change the border radius Any suggestion and What’s the problem??

How to limit a multi-select input field to a certain number selected

I have a multi-select field I want to limit a user to how many they can select. There are 15 options to choose from in the list but I only want users to select a maximum of 5. Here is my javascript so far.

I have checked the console in the developer tools and its just ignoring my code. What am I missing?

I’ve tried several iterations of the codes but its not working.

$(document).ready(function() {
  $('#ctl01_TemplateBody_WebPartManager1_gwpciMyAccount_ciMyAccount_AreasofExpertise_Name_Demo.GEO_SPEC').on('change', function(evt) {
    var selected = $(this).find('option:selected');
    if (selected.length > 5) {
      console.log("Warning: You can only select up to 5 options.");

      alert("You can only select up to 5 options.");

      $(this).val(Array.from(selected).slice(0, 5).map(option => option.value));
    }
  });
});

I cant seem to execute Javascript code on a Chrome Extension I made

Lately I have been coding a Chrome Extension that would refresh the page whenever certain component was present on the webpage, the code works perfectly, the problem comes when uploading the Extension

It seems to do nothing, not even the Console log

This is what the html looks like:

<html>
  <body>
    <script src="ad.js"></script>
  </body>
</html>

This would be the Javascript:

console.log("No hay anuncio");

/*const ad = document.getElementById("simple-ad-badge:d")
if(ad != null) {
    location.replace(location.href);
}else{
    console.log("No hay anuncio");
}*/

And this would be the manifest file:

{
  "manifest_version": 3,
  "name": "Ad",
  "description": "Ad",
  "version": "1.0",
  "action": {
    "default_popup": "ad.html",
    "default_icon": "hello.png"
  }
}

I have tried looking up what to add to make it work because I know there are parts missing that would allow the Extension to work, but I haven’t been able to find anything recent, everything is either for Manifest 2 or with outdated stuff

Nothing really ended up happening as I wasn’t able to find an answer

Get absolute filepath from relative path parsed from XML in JS

My use case is as follows

  • Parse an XML file in HTML via Form <input>.
  • XML file is verified based on xmlns.
  • From XML file get a series of file paths stored as relative paths.
  • For each path get the absolute file path so that only the files in the manifest file can be passed to an uploader function.

My issue is getting the absolute file paths from the string text from the <path> field.

XML

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<Manifest xmlns="http://my/xml/schema" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <Id>urn:uuid:b427a833-8a02-45e8-bf19-9178fe43bbfd</Id>
  <IssueDate>2023-12-05T14:47:29Z</IssueDate>
  <FileList>
    <File>
      <Id>urn:uuid:daf61762-d4b5-48c8-a845-cec748cc54d2</Id>
      <Path>filename.01.txt</Path>
    </File>
    <File>
      <Id>urn:uuid:818d7bfa-0b01-4538-8c55-c89e5972d38a</Id>
      <Path>filename.02.txt</Path>
    </File>
    ...
  </FileList>
</Manifest>

HTML

<form hx-encoding='multipart/form-data' hx-post='/API/v1/upload'
      _='on htmx:xhr:progress(loaded, total) set #progress.value to (loaded/total)*100'>
    <input type="file" id="file-selector" accept="*.xml">
    <button>
        Upload
    </button>
    <progress id='progress' value='0' max='100'></progress>
</form>

Javascript

    var file, xmlDoc;
    var URL = window.URL || window.webkitURL

    const file_xmlns = "http://my/xml/schema"
    const id = [];
    const fileList = [];

    const fileSelector = document.getElementById('file-selector');

    fileSelector.addEventListener('change', (event) => {

        const file = event.target.files[0];
        fileList.push(file)
        const fileUrl = URL.createObjectURL(file);

        fetch(fileUrl).then(res => {
                return res.text()
            }).then((xmlString) => {
                // do something with "text"
                xmlDoc = new DOMParser().parseFromString(xmlString,"text/xml");
                const xmlns = xmlDoc.lookupNamespaceURI(null);
                console.log("XMLNS: ", xmlns)
                if (xmlns !== file_xmlns) {
                    alert("Not correct file.")
                    return
                }
                console.log("correct file detected.")
                const assets  = xmlDoc.querySelectorAll("File")

            for (const asset of assets) {
                const i = asset.querySelector("Id").textContent;
                id.push(i);
                const paths = asset.querySelectorAll("Path");
                for (const p of paths) {
                    fileList.push(p.textContent);
                }
            }

            }).catch((e) => console.error(e));
    });

This is where I have gotten but am somewhat stumped as to where to go next. No doubt its easy when you know how! Any guidance appreciated.

Adding Titles to html table dropdown and text box from a Javascript function

The last part of my career was all back end ETL and programming. Now I am trying to create a web app (very slowly) in Javascript. I use WebStorm.

The following code works (no style yet), but I just want to add titles above the dropdown and text box. Many web searches have not yielded a solution. How do I add titles in this instance? Thanks!

function addRow(btn) {
    var parentRow = btn.parentNode.parentNode;
    var table = parentRow.parentNode;
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);
    // cell1 creation: element 1

    var dropdown1 = row.insertCell(0);
    //var element1 = document.createElement("input");
    // CREATE DROPDOWN of Status Choices
    var element1 = document.createElement("select");

    element1.type = "select";
    var one = document.createElement("option");
    one.innerHTML = "One";
    one.value = "1";
    element1.add(one, null);
    var two = document.createElement("option");
    two.innerHTML = "Two";
    two.value = "2";
    element1.add(two, null);
    var three = document.createElement("option");
    three.innerHTML = "Three";
    three.value = "3";
    element1.add(three, null);
    var four = document.createElement("option");
    four.innerHTML = "Four";
    four.value = "4";
    element1.add(four, null);
    // Add options to dropdown list
     dropdown1.appendChild(element1);
     // Text Box
    var textbox1 = row.insertCell(1);
    textbox1.title="Description";
    var element2 = document.createElement("input");
    element2.size = 50;
    element2.type = "text";
    // Append element2 to the right of element1
    textbox1.appendChild(element2);
}
<!--Table with addRow button-->
<table>
  <caption>This is the Table Caption</caption>
  <tr>
    <td>
      <button id="addRow" type="button" onClick="addRow(this)">Add</button>
      <label for="addRow">Add a Row</label>
    </td>
  </tr>
</table>

I tried many of the dot commands as well.

JavaScript method not execute ‘style.display=none’

I’ve an embedded app. This app wrote in JSP. There is a js file with the following code:

function openScanning() {
    document.getElementById('divModalScanning').style.display = 'block';
    startScan();
}

When i click the button, call this method, but the modal is not showing.

However, if a i comment the line “startScan()”, the modal is showing.

function openScanning() {
    document.getElementById('divModalScanning').style.display = 'block';
    //startScan();
}

I have no idea why this happens.
Can someone explain it to me?

I try to change to style.visibility = ‘visible’, but not effect.

Cookie on the same domain is set, but not being sent to another subdomain

I have a django server running on api.domain.lt and sveltekit server running on dev.domain.lt. Due to the separate servers I have a endpoint /csrf that forces to set a cookie if there’s none for the frontend, so I could perform any kind of POST requests later.

As I can see in the response headers the cookie is being set:

Set-Cookie csrftoken=d8nimJM2fXtyPdhra2h8oF36o7juCJKz; Domain=.domain.lt; expires=Tue, 28 Jan 2025 17:35:19 GMT; Max-Age=31449600; Path=/; SameSite=Lax; Secure

But when I perform another request to the server the cookie is not being added to the request,for god damn sakes, whyyyyyy? Even if I open the django server in another tab and view the Cookies in the dev tools, there’s nothing.

CORS_ALLOWED_ORIGINS = [
    "https://domain.lt",
    "https://dev.domain.lt",
    "https://api.domain.lt",
]


CSRF_TRUSTED_ORIGINS = [
    "https://domain.lt",
    "https://dev.domain.lt",
    "https://api.domain.lt",
]

# This allows us to send requests from dev.domain -> api.domain 
CORS_ALLOW_CREDENTIALS = True
CSRF_COOKIE_SECURE = True

# The cookie will be marked as “secure”, which means browsers may ensure that the cookie is only sent under an HTTPS 
SESSION_COOKIE_SECURE = True

# Is this actually doing anything?
CSRF_COOKIE_DOMAIN = ".domain.lt"
SESSION_COOKIE_DOMAIN = ".domain.lt"

This is how I perform a request to the django server:

const res = await fetch(
    "https://api.domain.lt/........",
    {credentials: 'include',}
);

HTML Contact Form Turnstile Validation

Hoping someone could help me have my Turnstile validation stop email being sent. Not sure how/where this should be done. Currently form has some basic validations thanks to bootstrap.

HTML:

<form class="p-3 p-xl-4" method="post" action="assets/php/contact-form.php">
    <div class="mb-3"><input id="name" class="shadow form-control form-control form-control form-control" type="text" name="name" placeholder="Name" required /></div>
    <div class="mb-3"><input id="email" class="shadow form-control form-control form-control form-control" type="email" name="email" placeholder="Email" required /></div>
    <div class="mb-3"><textarea id="message" class="shadow form-control form-control form-control form-control" name="message" placeholder="Message" required rows="6"></textarea></div>
    <div class="cf-turnstile" data-sitekey="0xSitekey"></div>
    <div><button class="btn btn-primary shadow d-block w-100" type="submit">Send</button></div>
</form>

PHP:

<?php
$name = $_POST[ 'name' ];
$email = $_POST[ 'email' ];
$message = $_POST[ 'message' ];
$subject = $_POST[ 'subject' ];
$content = "From: $name nEmail: $email nMessage: $message";
$recipient = "EMAIL@AD";
$mailheader = "From: $email rn";
mail( $recipient, $subject, $content, $mailheader )or die( "Error!" );
echo "<script type='text/javascript'> alert('Email sent!'); window.location.href = 'https:///index.html'; </script>";
?>

Why does my button not run a function after being clicked?

I’m using this code to make something happen when a button is pressed:

function serverSettingsButton(){
   console.log("test");
};
document.getElementById("server-settings-button").addEventListener("click", serverSettingsButton);

I’m getting zero output from the button, not even errors, as if I never even added the event listener.

Here is the HTML for the button:

<button id="server-settings-button" style="margin-left: 50%;font-size: xx-large;position: absolute;">Server Settings</button>

And also, in case it’s important, my page is being loaded like this:

document.getElementsByTagName("html")[0].innerHTML = data

I’ve looked everywhere and can’t find anything about this.

I’ve tried using onclick="serverSettingsButton()", I’ve tried using window.serverSettingsButton = function(){} and almost any other way you can think of assigning a function to a button but none of them seem to work.

Regex to check if url (with or without protocol) contains minimum one subpath/subdirectory

I need a regex to check that a URL string (with or without protocol) contains a minimum of one subdirectory/subpath.

Eg. valid:

https://google.com/abcde12345
https://www.google.com/abcde12345
http://google.com/abcde12345
http://www.google.com/abcde12345

Not valid:

https://google.com
https://google.com/
http://google.com
http://google.com/
http://www.google.com
http://www.google.com/
https://www.google.com
https://www.google.com/

This is my attempt:

const validUrlRegex = /^(https?://[^/]+(?:/[^/]+)?)?(www.)?[a-zA-Z0-9.-]+.[a-zA-Z]{2,}(/[^/]+)?/?$/