Ajax.Updater fetched content not shown in browser debugger

I am newly working on a fairly old system, which uses ColdFusion if it matters. In various places, it uses Ajax.Updater for server requests which return new HTML (.cfm) fragments to update the specified element with. This HTML also includes JavaScript via <script>‘s and inline event handlers, ie. <button onclick=...

The question is how can I go about debugging this code?

HTML (and .cfm) documents typically show up in the sources tab and can be debugged like normal JS, but in both Chrome and Firefox, the fetched HTML is not showing up. I can clearly see the new html being fetched in the network tab, the new elements are rendered and appear in the elements tab, and the actual JavaScript is clearly running as expected; it just doesn’t show up in the debugger.

Does fetched code simply never go to the debugger? Is it because the fetched html is a fragment? Is there some other known way to debug code from Ajax requested HTML?

Popup windows not appearing on button click

Recently, pop-up windows by themselves stopped working at the touch of a button.

Here is the html code

<div class="type t3" href="#type-popup-3" data-title="Подробная консультация<br />по варианту VIP" data-text="Заполните форму, и мы свяжемся<br />с вами для консультации по<br />варианту VIP" data-source="Консультация по варианту VIP" data-email="true">
<div class="type_text">
<span>Тип 3</span>
<em>Вариант VIP</em>
<a class="bttn">Подробнее</a>
</div>
</div>

Popup window code

<form id="type-popup-3" action="#" method="post" class="type-popup clearfix" data-btn="Получить консультацию" data-form="Консультация по Типу ККЗ" data-title="Подробная консультация" data-text="Заполните форму, и мы свяжемся с вами для консультации">
            <input type="hidden" class="reciever" name="reciever" value=""/>
            <input type="hidden" class="form_type" name="form_type"/>
            <input type="hidden" class="button_source" name="button_source"/>
            <input type="hidden" name="utm_source" class="utm_source">
            <input type="hidden" name="utm_medium" class="utm_medium">
            <input type="hidden" name="utm_campaign" class="utm_campaign">
            <input type="hidden" name="utm_content" class="utm_content">        
            <div class="tp_left">
                <span>text</span>
                <em>text</em>
            </div>
            <div class="tp_right">
                <div class="popup_h1">text</div>
                <div class="popup_h2">
                    text
                </div>
                <div class="inputs-wrap">
                    <div class="desc desc_name">Ваше имя</div>
                    <input type="text" name="name" required placeholder="Иван Иванов">
                    <div class="desc desc_phone">Ваш телефон</div>
                    <input type="text" name="phone" required placeholder="+7 (926) 123-58-99">
                    <div class="desc desc_email">Ваш e-mail</div>
                    <input type="email" name="email" required placeholder="[email protected]">
                    <input type="hidden" name='hub_form_type' value='Заполните форму, и мы свяжемся с вами для консультации 1'>
                    <a class="submit bttn fullsize" href="#">Получить консультацию</a>
                    <div class="form-status"></div>
                </div>
            </div>
        </form>

But when the button is pressed, nothing happens.

How to call a function with an event handler if the function requires the event to compile

I am currently working on a project where I need to call a script function on an event. This function is called when text is pasted into a textarea. The function copies the pasted text into an array and iterates through the array looking for the code value of Unicode right apostrophe (8217). It then replaces any found right apostrophe’s with a single quote. The function works as expected. However I am running this function on 8 different pages and want to clean my code up. I placed the script into a js file that is called on every page in the project so if any more cases it is needed are found it will be easy to implement.

The function is being called with:

<script>
    var instructions = document.getElementById("specialInstructions");
    instructions.addEventListener("paste", pasteToPlainText);
</script>

The function in the js file is:

function pasteToPlainText(event){
    var plainText;
    var replaceList;
    replaceList = new Array();
    
    //converts the pasted text to plain text
    if (event.clipboardData && event.clipboardData.getData){
        
        plainText = event.currentTarget.clipboardData.getData('text/plain');
    }else if (window.clipboardData){
        
        plainText = event.currentTarget.clipboardData.getData('text/plain');
    }
    
    for (var index = 0; index < plainText.length; index++){
        
        var rightApostropheCheck = plainText.charCodeAt(index);
        //Unicode for right apostrophe is 8217 (Used in outlook email)
        //Without this conversion a right apostrophe is put on screen.
            // The note is unable to save with a right apostrophe
        if (rightApostropheCheck == 8217){
            // replaces a right apostrophe with a single quote (apostrophe)
            replaceList.push("'");
        }else{
            // pushes all other text to the list that is printed to screen
            replaceList.push(plainText[index]);
        }
    }
    event.preventDefault();

    if (event.clipboardData) {
        
        content = replaceList.join("");
        document.execCommand('insertText', false, content);
        
    }else if (window.clipboardData) {
        
        content = replaceList.join("");
        document.selection.createRange().pasteHTML(content);
    }   
}

I get the error: Uncaught TypeError: Cannot read properties of undefined (reading ‘clipboardData’)
On the first if statement.

Any help or advice will be greatly appreciated. Thank you.

Github pages responds with 404 error for three.js canvas and imports

When trying to host my webpage with a three.js background, everything loads properly when hosted locally but as soon as I push it up to github pages nothing loads – just html.

I am using vite to package my code, and gh-pages to deploy the ‘dist’ folder to the hosted branch. I have tried changing the urls of all images and assets to ‘/image’ and storing the images in a public folder inside the root folder, as vite recommends. I run
$ npm run build, and
$ npm run preview
and everything looks good. I run npm run deploy (I added a deploy script in package.json, deploy: ‘gh-pages -d dist’), and then host the gh-pages branch on github pages and only the html shows up, and the console shows multiple 404: file not found errors.

Repo

The hosted code is on the gh-pages branch, if that hasn’t been clear already.

Limit the number of characters

My React app has a user input field. The field is made in such a way that the user enters data, they are displayed, and if desired, he can delete them. I did this functionality using evergreen-ui (Tag Input)(https://evergreen.segment.com/components/tag-input#custom_tag_submit_key).

Everything works well, only the problem is that if the user enters a value that is too long, then when the entered data is displayed, everything goes beyond the field boundaries.

enter image description here

In this regard, the question is, can I somehow limit the output value to the number of characters I need, so that the structure would not be violated

enter image description here

    export default function FilterStatusCode() {
  const [values, setValues] = React.useState([]);

  const [isExpanded, setIsExpanded] = useState(false);

  const toggleExpand = () => {
      setIsExpanded(!isExpanded);
  };

  return <>
    <div className="item-toggle-statuscode" onClick={toggleExpand}>
        <h6>Status Code</h6>
        { isExpanded ? <span class="material-icons">
            arrow_drop_up
          </span> :  <span class="material-icons">
            arrow_drop_down
          </span> }
          
    </div>
    { isExpanded &&
      <div>
        <TagInput
        separator="values"
          inputProps={{ placeholder: 'Add status code...' }}
          values={values}
          onChange={(values) => {
          setValues(values)}}>
        </TagInput>
      </div>
    }
</>;
}

Is it possible to enter dark mode and after switching pages dark mode stays on with only one js file?

So, I have several web pages and want them to stay dark, if dark mode is turned on on another page. So, I added one js script to all my HTML-files and it didn’t work at all. After that, I tried to add this script to only one HTML-file and it stayed dark after reloading the page, but, obviously, it hadn’t affected other pages.
How can I change the script to make it work and where is the problem?
Script:


if(localStorage.getItem("theme")==null){
    localStorage.setItem("theme", "light");
}

let localData = localStorage.getItem("theme");

if (localData == "light") {
    icon.src = "images/moon.png";
    document.body.classList.remove("dark-theme");
}
else if (localData == "dark") {
    icon.src = "images/sun.png";
    document.body.classList.add("dark-theme");
}

icon.onclick = function () {
    document.body.classList.toggle("dark-theme");
    if (document.body.classList.contains("dark-theme")) {
        icon.src = "images/sun.png";
        localStorage.setItem("theme", "dark");
    }
    else {
        icon.src = "images/moon.png";
        localStorage.setItem("theme", "light");
    }
} ``` 

WebRTC peerConnection ontrack listener doesn’t trigger

First of all, issue here is different from all I found in “google” as I’m using Spring Boot as signaling server to connect two different browser’s tabs.
Peers seem to be connected and messages are sent correctly. However, when I run sendStream with button, second tab track event listener doesn’t trigger.

//connecting to our signaling server 
var conn = new WebSocket('ws://localhost:8080/socket');

conn.onopen = function() {
    console.log("Connected to the signaling server");
    initialize();
};

conn.onmessage = function(msg) {
    console.log("Got message", msg.data);
    var content = JSON.parse(msg.data);
    var data = content.data;
    switch (content.event) {
    // when somebody wants to call us
    case "offer":
        handleOffer(data);
        break;
    case "answer":
        handleAnswer(data);
        break;
    // when a remote peer sends an ice candidate to us
    case "candidate":
        handleCandidate(data);
        break;
    default:
        break;
    }
};

function send(message) {
    conn.send(JSON.stringify(message));
}

var peerConnection;
var dataChannel;
var input = document.getElementById("messageInput");

function initialize() {
    var configuration = null;

    peerConnection = new RTCPeerConnection(configuration);

    // Setup ice handling
    peerConnection.onicecandidate = function(event) {
        if (event.candidate) {
            send({
                event : "candidate",
                data : event.candidate
            });
        }
    };

    const remoteVideo = document.getElementById('video');

    peerConnection.addEventListener('track', async (event) => {
        const [remoteStream] = event.streams;
        remoteVideo.srcObject = remoteStream;
        console.log("STREAM RECEIVED");
    });

    peerConnection.ontrack((e))

    // creating data channel
    dataChannel = peerConnection.createDataChannel("dataChannel", {
        reliable : true
    });

    dataChannel.onerror = function(error) {
        console.log("Error occured on datachannel:", error);
    };

    // when we receive a message from the other peer, printing it on the console
    dataChannel.onmessage = function(event) {
        console.log("message:", event.data);
    };

    dataChannel.onclose = function() {
        console.log("data channel is closed");
    };
  
    peerConnection.ondatachannel = function (event) {
        dataChannel = event.channel;
    };
    
}

function createOffer() {
    peerConnection.createOffer(function(offer) {
        send({
            event : "offer",
            data : offer
        });
        peerConnection.setLocalDescription(offer);
    }, function(error) {
        alert("Error creating an offer");
    });
}

function handleOffer(offer) {
    peerConnection.setRemoteDescription(new RTCSessionDescription(offer));

    // create and send an answer to an offer
    peerConnection.createAnswer(function(answer) {
        peerConnection.setLocalDescription(answer);
        send({
            event : "answer",
            data : answer
        });
    }, function(error) {
        alert("Error creating an answer");
    });

};

function handleCandidate(candidate) {
    peerConnection.addIceCandidate(new RTCIceCandidate(candidate));
};

function handleAnswer(answer) {
    peerConnection.setRemoteDescription(new RTCSessionDescription(answer));
    console.log("connection established successfully!!");
};

function sendMessage() {
    dataChannel.send(input.value);
    input.value = "";
}

async function sendStream() {
    const localStream = await navigator.mediaDevices.getUserMedia({audio: false, video: true});
    localStream.getTracks().forEach(track => {
        peerConnection.addTrack(track, localStream);
        console.log("STREAM SENT")
        const localVideo = document.getElementById('video2');
        addVideoStream(localVideo, localStream);
    });
}

function addVideoStream(video, stream) {
    video.srcObject = stream;
    video.addEventListener('loadedmetadata', () => {
        video.play();
    })
}

React hook only when props change? useEffect not work

I have component where need to check every time data props and if data is changed i need to set new values for it. UseEffect not work

export const renderData = ({data}) => {
   useEffect(() => { 
    if (data.length < 1) { 
      data =[{id: 1, name: 'test'}]; 
    }
  }, [data]);
}

Code above no work, but code below work ( just without useEffect )

export const renderData = ({data}) => { 
    if (data.length < 1) { 
      data =[{id: 1, name: 'test'}]; 
    } 
}

get matrix from html form

I have an html form. How can I get a matrix from it to use it in a php function? I have a js function that does the same thing. But how to do it in php? Can I somehow pass the returned matrix from js to php?

function getInputByMatrix() {
    const rows = document.getElementById('mrow').value;
    let input = [];
    for (let i = 1; i <= rows; i++) {
        input[i-1] = [];
        for (let j = 1; j <= rows; j++) {
            input[i-1][j-1] = document.getElementById(`a${i}${j}`).value;
        }
    }
    return input;
}

My javascript regex code does not work for mobile view

I used the following code in WPforms on WordPress to only allow english characters, numbers and space char in my form. Everything works great until you try it from mobile (the same website and same form, Chrome on Android for example), it just does not work and allows you to fill out any character to the fields.. is there any way to prevent it? I mean to make it work for mobile and don’t allow visitors to put special characters from mobile too?

function wpf_dev_char_restrict() {
?>
 
<script type="text/javascript">
     
    jQuery(function($){
        $( '.wpf-char-restrict' ).on( 'keypress', function(e){
             
            var regex = new RegExp('^[a-zA-Z0-9 ]+$');
            var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
             
            if (!regex.test(key)) {
                alert ( "Please fill out the form in English. Thank you!" ); // Put any message here
                e.preventDefault();
                return false;
            }
        });
         
        //Prevent any copy and paste features to by-pass the restrictions
        $( '.wpf-char-restrict' ).bind( 'copy paste', function (e) {
             
            var regex = new RegExp('^[a-zA-Z]+$');
            var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
             
            if (!regex.test(key)) {
                alert ( "Pasting feature has been disabled for this field" ); // Put any message here
                e.preventDefault();
                return false;
            }
        });
         
    });
 
</script>
 
<?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_dev_char_restrict', 10 );

“Allowed to navigate” algorithm in whatwg

I’am trying to realize when browser will throw an error due with allowed to navigate algorithm. Unfortunately, I don’t understand its complex conditions.

A browsing context A is allowed to navigate a second browsing context B if the following algorithm returns true:

  1. If A is not the same browsing context as B, and A is not one of the
    ancestor browsing contexts of B, and B is not a top-level browsing
    context
    , and A’s active document‘s active sandboxing flag set has
    its sandboxed navigation browsing context flag set, then return
    false.

  2. Otherwise, if B is a top-level browsing context, and is one of the ancestor browsing contexts of A, then:

    1. If A’s active window has transient activation and A’s active document‘s active sandboxing
      flag set
      has its sandboxed top-level navigation with user activation
      browsing context flag
      set, then return false.

    2. Otherwise, if A’s
      active window does not have transient activation and A’s active
      document
      ‘s active sandboxing flag set has its sandboxed top-level
      navigation without user activation browsing context flag set
      , then
      return false.

  3. Otherwise, if B is a top-level browsing context, and is neither A
    nor one of the ancestor browsing contexts of A, and A’s Document’s
    active sandboxing flag set has its sandboxed navigation browsing
    context flag set
    , and A is not the one permitted sandboxed navigator
    of B, then return false.

  4. Return true.

If anybody knows how to present and show every condition with understanable language, I would be glad. Also if it possible – could you express this with js code

Unable to execute another query while iterating the first query

I need to execute another query while iterating the first query as follows, but I keep getting an error “const error = this._ending ? new Error(‘Connection terminated’) : new Error(‘Connection terminated unexpectedly’)”. The query is not a final query. I am just testing it out.

const client = new Client(credentials)
await client.connect()

const userQuery = await client.query('select c.* from clients c')
const rows = userQuery.rows
rows.forEach(async row => {
    console.log("user", row)
    const orderQuery = await client.query(`select o.created from orders o where o."userId" = ${row.id} order by o.created desc limit 1`)
    const orderRows = orderQuery.rows
    orderRows.forEach(order => {
        console.log(order)
    })
})
await client.end()

is there a way to execute another query while iterating the first query?

NestJS logs have weird characters in log-management tools

a simple question with a possibly simple answer I just cant seem to find:

We’re using NestJS as our server-side javascript framework for a micro-service based infrastructure.

Working locally with the built in NestJS logger, or with our own class extending and implementing the logger functions, the console seems to print out the logs exactly as expected, for example:

[Nest] 41477  - 06/01/2022, 5:46:39 PM     LOG [Bootstrap] Mapped {/api/v1/accounts/:accountId/positions/:positionId/matches, GET} route

However, when running these service on cloud platforms, many (if not all) show-me-the-pod-logs tools add many “special” characters, for example:

[32m[Nest] 19  - [39m06/01/2022, 3:29:51 PM [32m    LOG[39m [38;5;3m[RouterExplorer] [39m[32mMapped {/api/v1/accounts/:accountId/positions/:positionId/matches, GET} route[39m[38;5;3m +1ms[39m

As you can see, it’s almost the same, but not quite..
what are all of these [32m and [39m being added all over the place?
This appears to be the same case in many of our tools: Datadog, ArgoCD pod logs, Rancher pod logs, etc.

What are these, and how can we get rid of them?

Is it possible to use an external axios handler with createAsyncThunk

I have a API handler with different functions using Axios for get, post, patch, etc. I want to use those API handler with createAsyncThunk from redux toolkit, is this possible?

it would be something like

export const paymentMethods = createAsyncThunk(
  'tenants/payments',
  async (ppp: any, { dispatch, getState }) => {
    const x = await postRequest(
      `${API.TENANTS}/${ppp.tenantId}/${API.PAYMENT_METHODS}`,
      response => console.log(response),
      ppp.data,
    );
    return x.data;
  },
);

The thing here is that createAsyncThunk handles rejected, fulfilled and pending response promises but if I use this configuration it will always return fulfilled even though the call actually fails.