How to dispatched an Input event for a contenteditable and have it work?

I am trying to make text bold in a content editable by a button click.

const e = document.querySelector('#e');
const b = document.querySelector('#b');

e.addEventListener('input', (event) => {
  console.log('---');
  console.log('isTrusted', event.isTrusted);
  console.log('inputType', event.inputType);
});

b.addEventListener('click', (event) => {
  e.dispatchEvent(new InputEvent('input', {
    bubbles: true,
    cancelable: true,
    composed: true,
    inputType: 'formatBold',
  }));  
});
<button id="b">B</button>
<div id="e" contenteditable="true">
Hello World
</div>

I’m testing in Safari on MacOS:

If I highlight the word hello, right-click, select “Font” from the menu, then select “Bold”, the highlighted word hello will bold. I will also see the input event as expected.

If I highlight the word hello, click the “B” button, the highlighted word hello will not bold. I still see the event as expected (but it is not trusted).

How do I dispatch an input event and have it work?

I booked 8:00AM – 12:00PM with a duration of 4 hours. How can I disable/hide the covered time within the 8:00AM – 12:00PM? Ex: 8:00AM – 9:00AM 1hour

                                    <form id="duration-form" method="post">
                                        <label for="duration">Enter Duration (in hours):</label>
                                        <input style="text-align:center;" class="form-control" type="number" id="duration" name="duration" value="<?php echo $duration / 60; ?>">
                                        <input style="text-align:center;" class="btn btn-secondary btn-sm" type="submit" value="Enter">
                                    </form>
                                        <p>Select timeslot:</p>
                                    <?php 
                                        $timeslots = timeslots($duration, $cleanup, $start, $end);
                                            foreach ($timeslots as $ts) {
                                    ?>
                                   
                                    <div class="col-md-12">
                                        <div class="form-group">
                                           
                                            <?php if (in_array($ts == '', $bookings)) { ?>
                                                <button  class="btn btn-danger btn-sm"><?php echo $ts;?></button>
                                            
                                            <?php } elseif ($duration == 0 ) {?>
                                    
                                            <?php } else { ?> 
                                                <button class="btn btn-primary btn-sm book" data-timeslot="<?php echo $ts;?>"><?php echo $ts;?></button>
                                    
                                            <?php } ?>
                                             
                                        </div>
                                    </div>
                                    <?php } ?>

When I put duration, it will display the timeslot and change depends on how many hours you input. Once I booked, timeslot will stored in database. $bookings will check if specific $ts (timeslot) is already booked, then the button will turn into danger/disabled. I want to disabled/ turn to danger button those covered time on booked timeslot.

I tried some codes but it won’t fetch any of timeslot inside in_array $ts.

drawing eclipse in P5.js

I am trying to create a stary night behind a lunar eclipse but the orientation of the starts is off. Right now the stars are in the bottom right hand corner. I think the it has to do with “translate” Any suggestions?

let slider ;
let val ;
var stars = [];

function setup() {
  createCanvas(600, 600);
  slider = createSlider(-80,0,-80);
  slider.position(10,10);
  slider.style('width', '100px');
  slider.style('border-radius', '50&');
  colorMode(HSB);

  
  for (var i = 0; i < 100; i++) {
        stars[i] = new Star();
    }
}

function draw() {
  background(30);
  
  val = slider.value();
  
  background(color(204,30,map(abs(val),0,80,10,80)));
  translate(width/2,height/2);
  
  fill('yellow');
  circle(0,0,80);
  //fill(color(204,30,map(abs(val),0,80,10,80)));
  //stroke(color(205,30,map(abs(val),0,80,50,90),.3));
  fill('white');
  circle(val,0,80);
  

    
    for (var i = 0; i < stars.length; i++) {
        stars[i].draw();
     
    }
}


// star class //
class Star {
    constructor() { 
      
        this.x = random(width);
        //this.x = (width);
        this.y = random(height);
        this.size = random(.25,3);
        this.t = random(TAU);
    }
    
    draw() {
        this.t += 0.1;
        var scale = this.size + sin(this.t) * 2;
        noStroke();
        ellipse(this.x, this.y, scale, scale);
    }
  
}

When the moon passes over the sun using the slider, the daylight should fade and the stary night time sky should appear.

Instatiating custom built-in element in JavaScript does not work

I’ve crafted a custom built-in element that recursively invokes itself. However, the child elements generated in JavaScript are not inheriting from the custom built-in element. Given that the initial invocation from HTML is functioning correctly, I suspect the issue may stem from the page lifecycle when adding controls via JavaScript. Any thoughts on why this could be occurring?

html

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

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

<body>
    <ul is="test-list" id="testList">

    </ul>
    <script type="module" src="/js/test-list-element.js"></script>

    <script>
        let data = [
            {
                name: 'a',
                data: [{
                    name: 'a',
                    data: []
                },
                {
                    name: 'b',
                    data: []
                },
                {
                    name: 'c',
                    data: []
                },
                {
                    name: 'd',
                    data: []
                }]
            },
            {
                name: 'b',
                data: [{
                    name: 'a',
                    data: []
                },
                {
                    name: 'b',
                    data: []
                },
                {
                    name: 'c',
                    data: []
                },
                {
                    name: 'd',
                    data: []
                }]
            },
            {
                name: 'c',
                data: [{
                    name: 'a',
                    data: []
                },
                {
                    name: 'b',
                    data: []
                },
                {
                    name: 'c',
                    data: []
                },
                {
                    name: 'd',
                    data: []
                }]
            },
            {
                name: 'd',
                data: [{
                    name: 'a',
                    data: []
                },
                {
                    name: 'b',
                    data: []
                },
                {
                    name: 'c',
                    data: []
                },
                {
                    name: 'd',
                    data: []
                }]
            },
        ];

        window.onload = (event) => {
            let listElement = document.getElementById("testList");
            listElement.data = data;
        }
    </script>

</body>

</html>

test-list-element.js

class testList extends HTMLUListElement {
    constructor() {
      super();
      this.render = this.render.bind(this);
    }
  
    #data = null;
    set data(value) {
      this.#data = value;
      this.render();
    }

    render(){
        if(!this.#data) return;

        this.#data.forEach(element => {
            let newItem = document.createElement('li');
            newItem.innerText = element.name;
            this.appendChild(newItem);

            if(element.data)
            {
                let newlist = document.createElement('ul');
                newlist.setAttribute('is','test-list')            
                newlist.data = data;
                newItem.appendChild(newlist);
            }
        });
    }
}

    
customElements.define('test-list', testList, { extends: 'ul' });
  

enter image description here

Fortify Cross-Site Script DOM Finding | Proper way to handle the finding

We have a Fortify finding for: Cross-Site Scripting DOM.

Here is the code:

function applyFormatting(ruleObject) {
    element = ruleObject.TargetElement

    if (element) {
        if (ruleObject.BackgroundColor) {
            $(element).css('background-color', ruleObject.BackgroundColor); 
        }
        if (ruleObject.TextColor) {
            $(element).css('color', ruleObject.TextColor); 
        }
    }
}

It is a finding on line $(element).css('background-color', ruleObject.BackgroundColor); and $(element).css('color', ruleObject.TextColor);.

For ruleObject.TextColor and ruleObject.BackgroundColor

Example values in the database are: #f52f3c and #1896f0

You cannot write normal InjectSafeHTML code because of the # of the color hex code that is required.

What is a valid way to handle this finding?

This is a requirement of our application.

React: call onChange hook initially, the same time defaultChecked is set


let radio_onchange = (e) => {
    variable.radio = radio_name;
    if (on_update) on_update();
};

let radio_defaultChecked = variable_index === radio_index;

return (
    <Fragment key={radio_index}>        <input type='radio'               name={radio_id + '-' + radio_name}
               value={radio_name}
               defaultChecked={radio_defaultChecked}
               onChange={radio_onchange}
        />    </Fragment>);


On change, the radio button has a side effect, which is setting variable.radio to radio_name.

Now defaultChecked only sets checked of the radio initially, that is when the component first mounts.
I also want to trigger onchange’s side effect just at that moment, when it initially loads.

I could use something like useEffect with no dependencies, but the code above is two loops deep (iterating over n variables and k radios) so when I use useEffect just below radio_defaultChecked to call radio_onchange, that throws some errors like

Warning: React has detected a change in the order of Hooks called by VariableForm. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks

What would be the best way to resolve this? To extract each (variable, radio) tuple into its own component which uses useEffect to only initially set variable.radio?

can connect to mongodb compass locally but not on live server vs code

Im trying to make a simple login were user enter username and pass word and it goes into my mongodb database. It woks fin locally but when use live server it gives me this error:
Failed to load resource: the server responded with a status of 405 ()

//index.js
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const bodyParser = require("body-parser");

app.use(bodyParser.urlencoded({extended: true}));


//dbconnection //and database name 
mongoose.connect("mongodb+srv://DavLiendo:<password>.uoiprx8.mongodb.net/player_profiles", {
    
});

// Define a schema
const sch={
    username:String,
    password:String

}
// Define a model based on the schema  //handles collection name and schema
const monmodel = mongoose.model("logins",sch)

app.get("/",function(req, res){
    res.sendFile(__dirname + "/login.html");
})

app.post("/", function(req, res) {
    let newnode = new monmodel({
        username: req.body.username,
        password: req.body.password
    });
    newnode.save();
    res.redirect("/");
})


app.listen(5500, () => {
    console.log("Server is running on port 5500");
});




login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
    <!-- Login form -->
    <div id="loginScreen">
    <form class="container" method="post" action="/">
        <h1>Login</h1>
        <input type="text" id="username" name="username" placeholder="Username" required>
        <input type="password" id="password" name="password" placeholder="Password" required>
        <button type="submit">Login</button>
    </form>
</div>
</body>
</html>

Is it possible to invoke chrome.tabs.captureVisibleTab to take screenshot when user open new tab without clicking extension icon?

I’m building a chrome extension and I want to implement the function users can take screenshot automatically when they open new tab. I want to achieve it without invoking the extension(by clicking extension icon).

My current code is as below. I can take screenshot when I switch tabs, but I get error when I open new tab. Error is:

`The 'activeTab' permission is not in effect because this extension has not been in invoked.`

//background.js

const captureScreenshot = (tabId) => {
  chrome.tabs.get(tabId, (tab) => {
    if (!chrome.runtime.lastError && tab && tab.status === "complete") {
      chrome.tabs.captureVisibleTab(null, { format: "png" }, (dataUrl) => {
        if (chrome.runtime.lastError) {
          console.error(chrome.runtime.lastError.message);
          return;
        }
        console.log("Screenshot captured for tab ID:", tabId);
        console.log("Screenshot data URL:", dataUrl);
      });
    } else {
      console.warn("Unable to capture screenshot for tab ID:", tabId);
      console.warn("Tab status:", tab ? tab.status : "unknown");
    }
  });
};

//take screenshot when user switch tab, it works.
chrome.tabs.onActivated.addListener((activeInfo) => {
  setTimeout(() => {
    console.log("Tab activated:", activeInfo);

    captureScreenshot(activeInfo.tabId);
  }, 500);
});

//take screenshot when user open new tab. it doesn't work
chrome.tabs.onCreated.addListener((tab) => {
  setTimeout(() => {
    console.log("New tab created:", tab);
    captureScreenshot(tab.id);
  }, 500);
});

I guess I can’t use chrome.tabs.captureVisibleTab when it’s new tab, without clicking extension icon.
So I’m thinking it might be possible with html2canvas and read this . But it’s not so obvious how to achieve my goal with this..

primeng dialogue component does not render when triggered

i’m using primeng’s dialogue component, in the documentation for it they use a data bound boolean to render it, i did that, the button does trigger the show dialogue function but the dialogue does not render.
here is the type script variable and function:

 dialog: boolean = false;
  openNew() {
this.dialog = true;
console.log('this.openNew() called'+ this.dialog)

}

and here is the html code for the components:

<p-dialog [(visible)]="dialog" [style]="{ width: '450px' }" header="Product Details" [modal]="true" styleClass="p-fluid">

the button triggers the function normally but the dialogue does not render.

Is there a way to fire a function in React when user enter new URL to go to different part of the app?

I have a React application(with supabase) and I’m trying to logout user when they enter a new url.

For instance.

I want user only see /share/page. but if they are trying to enter new url like /dashboard I want the app to completely signout.

What I did try.

  • using useLocation from react-router-dom. wrapped in useEffect but seem like it not firing when user enter new url.

    useEffect(() => {
      supabase.auth.signOut();
    }, [location.pathname]);
    
  • beforeunloadeven listener not trigger as well.

    useEffect(() => {
      const handleBeforeUnload = () => {
        supabase.auth.signOut();
      };
      window.addEventListener('beforeunload', handleBeforeUnload);
      return () => {
        window.removeEventListener('beforeunload', handleBeforeUnload);
      };
    }, []);

I assume that when the new url entered and user press enter, React will perform full page reload. At the time of the reload, user already on to a new component which make all useEffect(inside the component that I expected user to see) not trigger.

Is there anyway other way to do this?

index.html cannot import function from a javascript file? [closed]

I am trying to use Firebase auth and firestore for a project. I have created an index.html and a forms.js (along with the css ofc) and I have a button in Index.html that takes an email and password.
I then have an onClick to call a function from forms.js but it doesn’t work and I can’t figure out why…

The forms.js

The index.html

it keeps giving me this error: Uncaught ReferenceError: login is not defined
at HTMLButtonElement.onclick (index.html?_ijt=aptrjkoe7masd9fibils804p0d:18:31)

I have defined it and it even shows blue so it is being referenced and I don’t know i’ve spent so long on this. Anything would help im a beginner lost lol.

Tried mr GPT but it doesn’t give any help (ofc) and just repeats back my code…

How do you allow SSO when originating from an iframe in 2024?

I have an app that runs on example.com and you can log into it via SSO. You can also embed example.com into any website you want. When a user needs to log into example.com via SSO we open a new window and then, normally, that window uses window.opener.postMessage() to let the iframe know when it’s done and send back a login token. This has the following issues:

  1. Sometimes with Google OAuth, the popup window has the window.opener set to null. Not sure why but when this happens we obviously can no longer post a message back.

  2. So then people say to use BroadcastChannel to communicate back to the API, however, Chrome now has partitioned BroadcastChannel so – if you are an the iframe in this case your sandbox is for randompage.com > example.com and so you cannot communicate from the popup back to the iframe through BroadcastChannel.

So how is this supposed to be done now?

Using the window.opener method, posting back works in most cases, but Google OAuth can set opener to null. BroadcastChannel with iframes seems to be partitioned and this wont’ be a reliable source forward.

Deployed react project with panel manager

I created a react website and a panel to manage the website with react. These two projects are separate. How do I deploy
I tried to build from two projects
How should the server or host be? How can I solve this problem?

Thank you for your attention