HTMLCollection does not function for loops [duplicate]

I encountered a problem of making a for loop after a document.getElementsByClassName(“..”)

document.addEventListener('DOMContentLoaded', function() {
let btnTitle = document.getElementsByClassName("button-title");
console.log("Number of button-title elements found:", btnTitle.length);
if (btnTitle) {
    console.log("all button: ", btnTitle);
    Array.from(btnTitle).forEach((btn) => {
        console.log("btn", btn);
        btn.addEventListener("click", (event) => {
            const courseContent = btn.nextElementSibling;
            console.log("courseContent:", courseContent)
            courseContent.classList.toggle('show');
        })
    })
}
}

It will be returning like the image

Image of console

I don’t understand why btnTitle.length return 0, but it still has btnTitle in console, and it has one element who owns a length: 1. I did it because I want to debug why the button’s function is not working

And this is how I create the buttons by javascript (if it’s necessary to debug):

    const courseAndTest = document.getElementById("course_and_test");
if(courseAndTest) {
    //Fetch data
    const student_id = courseAndTest.dataset.studentId;
    fetch(`/student_tests/${student_id}`)
        .then(response => response.json())
        .then(data => {
            if (!data || !data.courses) {
                courseAndTest.innerHTML = "<p>No courses found.</p>";
                return;
            }

            //Make div for each course
            data.courses.forEach(course => {
                let course_nb = 0
                const course_container = document.createElement("div");
                course_container.innerHTML += `<button class="btn btn-primary button-title"><h3>Course ${course_nb += 1}: ${course.course.title}</h3></button>`
                const course_container_2 = document.createElement("div");
                course_container_2.classList.add("toggle-course");
                //Add all lectures of course
                course.lectures.forEach(lecture => {
                    const lecture_container = document.createElement("div");
                    lecture_container.style.overflowX = "auto";
                    lecture_container.innerHTML += `<h4>${lecture.title}</h4>`

                    //create a table with the lecture test score
                    const lecture_table = document.createElement("table");
                    lecture_table.classList.add("lecture-table", "table", "table-hover");
                    //create header for the table
                    lecture_table.innerHTML += `
                    <tr>
                        <th scope="col">Number</th>
                        <th scope="col">Quiz</th>
                        <th scope="col">Score</th>
                    </tr>
                    `
                    lecture_container.appendChild(lecture_table);
                    
                    //Add quize's cell
                    let i = 0
                    lecture.quizes.forEach(quiz => {
                        const tableRow = lecture_table.insertRow();
                        tableRow.insertCell().textContent = i+=1;
                        tableRow.insertCell().textContent = quiz.title;
                        tableRow.insertCell().textContent = quiz.score;
                    });
                    lecture_container.appendChild(lecture_table);
                    course_container_2.appendChild(lecture_container);
                    course_container.appendChild(course_container_2);
                });
                courseAndTest.appendChild(course_container);
            });
        })
        .catch(error => {
            console.error("Error fetching data:", error);
            courseAndTest.innerHTML = "<p>Error loading courses.</p>";
        });

}

Why don’t my angular components realise that it’s part of a module?

Disclaimer: I may be wrong about my understanding of this seeing as I have only been using Angular for little over a year (Angular 16.0.0).

Code

I have this component (SidebarComponent):

@Component({
    selector: 'app-sidebar',
    templateUrl: './sidebar.component.html',
    styleUrls: ['./sidebar.component.scss']
})
export class SidebarComponent implements OnInit {
    ... // Not very relevant to the issue
}

This SidebarComponent is declared as part of a module (ShellModule):

@NgModule({
    declarations: [
        ...,
        SidebarComponent,
        ...
    ],
    imports: [
        CommonModule,
        RouterModule,
        ... // Other necessary modules that are used in the sidebar
        TranslatePipe,
    ],
    exports: [
        ...,
        SidebarComponent,
        ...
    ],
    schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
export class ShellModule {}

Issue

What I expect here is that the sidebar component can access imports from the module that declares it and that includes exports from RouterModule and TranslatePipe.

Note: The solution to import TranslateModule(.forChild()) doesn’t really work, I tried. Furthermore, I import the pipe only in other projects and it works dandy.

However, The errors i get are the following :

Error: src/app/components/shell/sidebar/sidebar.component.html:51:82 - error NG8004: No pipe found with name 'translate'.

51 {{'sidebar.' + sub_child.title | translate}}

  src/app/components/shell/sidebar/sidebar.component.ts:11:18
    11     templateUrl: './sidebar.component.html',
                        ~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component SidebarComponent.

                 ----------------------------------
Error: src/app/components/shell/sidebar/sidebar.component.html:48:51 - error NG8002: Can't bind to 'routerLinkActiveOptions' since it isn't a known property of 'span'.

48 <span [routerLinkActiveOptions]="{exact: true}" class="sidemenu-link"

  src/app/components/shell/sidebar/sidebar.component.ts:11:18
    11     templateUrl: './sidebar.component.html',
                        ~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component SidebarComponent.

Along with other issues concerning other html tags like, mat-panel-tilte, mat-expansion-panel… Which I’m sure are included in the module’s imports.

The reason why i’m suspicious of the component not realising that it’s a part of a module and has access to its imports and not an issue of paths or architecture is because when I tried to make the component standalone and have the pipe as its import it actually worked.

Conclusion

I want to understand why this and many other (not all) components from the same module don’t realise what is imported in the module and act as if they’ve never seen it. Also, if the standalone solution is actually the better way please let me know why because I’m still learning and would like to be better at this.

How to Avoid ‘unsafe-eval’ in CSP with jQuery AJAX get() and .js.erb in Rails?

I’m working on a Ruby on Rails 7.1 application and encountering an issue with Content Security Policy (CSP). When I make an AJAX request using get() in a .js.erb file, I get the following error in the browser console:

application-8846f773213213213332321321321323.js:83759 U**ncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive:** "script-src 'unsafe-inline' 'nonce-ewqe321PNhjdasdafdse2q3eurY42hk10fVB7en='".

The error occurs in this create.js.erb file:

  get("<%= action_button_index_path(object_type: @object_type, format: :js) %>");

This is my CSP configuration in config/application.rb:

Rails.application.configure do
  config.content_security_policy do |policy|
    policy.default_src :self, :unsafe_inline
    policy.font_src :self, "https://fonts.gstatic.com"
    policy.frame_src :self
    policy.script_src :unsafe_inline
    policy.script_src_elem :self, :unsafe_inline, "https://www.recaptcha.net"
    policy.connect_src :self, "*.nr-data.net"m"
    policy.style_src_elem :self, :unsafe_inline, "https://fonts.googleapis.com", "https://www.gstatic.com"
    policy.img_src :self, :unsafe_inline, "data:"
    policy.object_src :none
    policy.base_uri :self
    policy.report_uri "/csp_violation"
  end

  config.content_security_policy_nonce_generator = ->(_request) { SecureRandom.base64(32) }
  config.content_security_policy_nonce_directives = %w[script-src]
  config.content_security_policy_report_only = false
end

I want to avoid adding ‘unsafe-eval’ to my CSP because it weakens security against XSS attacks. How can I refactor my code to load or execute the JavaScript from widget_button_index_path(widget_type: @widget_type, format: :js) without requiring ‘unsafe-eval’? Ideally, I’d like a solution that works with my current setup (Rails, jQuery, and CSP with nonce).

Any suggestions or examples would be greatly appreciated! Thanks!

WebRTC ICE Candidates Not Settling on Receiver Side (React, Socket.io)

I am implementing a video call feature using two separate RTCPeerConnection instances for sending and receiving video. Currently, I have only implemented the sender’s RTC connection, meaning only the receiver can see the sender’s video.

Issue: ICE candidates are received on the receiver’s side but don’t seem to be applied properly. Tracks seem to be received, but no video is displayed.

reciever logs

reciever logs 2

sender logs

webrtc recievr

webrtc sender

function VideoFrameReciever() {
  const { match,  socket } = useAuthStore();
  const remoteVideoRef = useRef();
  const startCall = async () => {
     let candidates= null;
     const sendersPC = new RTCPeerConnection({
         iceServers: [
       { urls: "stun:stun.l.google.com:19302" }, 
       { urls: "stun:global.stun.twilio.com:3478" },
      ],
    });
  socket.on("receive-offer", async ({ sdp, from }) => {
     console.log("offer received");

     await sendersPC.setRemoteDescription(sdp);
     const answer = await sendersPC.createAnswer();
     await sendersPC.setLocalDescription(answer);
     socket.emit("send-answer", {sdp: sendersPC.localDescription,to: match,      
     });

Not able to use the LiveUpdate Capacitor plugin for self hosted services | Capacitor Live Update Plugins

I have a Vue.js-based application and I am using Capacitor to build the mobile app.

The mobile application is working fine as expected but I am facing an issue with using the live-update plugin using self-hosted not capawesome cloud.
I have read the documentation from here

To get the latest version, I have the following file on my self-hosted server

app-versions.php

<?php
header('Access-Control-Allow-Origin: *'); 
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');

$data = [
    ["version" => "8.1.27"],
    ["version" => "8.1.28"],
];
header('Content-type: application/json');
echo json_encode($data);
?>

based on this, I have the following code in my main.js

import { LiveUpdate } from '@capawesome/capacitor-live-update';

const getBundleInfo = async () => {
    try {
        const request = await fetch("https://example.com/app-versions.php", {
            method: "GET",
            headers: {
              "Content-Type": "application/json",
              "Accept": "application/json",  
            }
        })
        const result = await request.json();
        let appVersion = version;
        if (result.length > 0) {
            appVersion = result[result.length - 1].version
            alert("Latest version is: " + appVersion)
        }
        return appVersion;
        
    } catch (error) {
        alert(error)
    }
}

(async () => {
    if (Capacitor.isNativePlatform()) {
        try {
            const result = await LiveUpdate.getCurrentBundle();
            // this result is always {bundleId: null}
        } catch (error) {
            alert(error)
        }

        try {
            const version = await getBundleInfo();
            await LiveUpdate.downloadBundle({
                url: `https://example.com/build-v${version}.zip`,
                bundleId: version,
            });
            await LiveUpdate.ready();
            await LiveUpdate.reload();
        } catch (error) {
            alert(error)
        }
    }
})();

Issues:-

  • The LiveUpdate.getCurrentBundle(); always returns {bundleId: null} for self-hosted.
  • If I call the setBundle() then it always says “LiveUpdate.setBundle() is not implemented on ios”.
    enter image description here
  • It is very difficult to know when should I download the new bundle because the applied bundle is always null.
  • I rely on the exception of the downloadBundle function so when I get the error “Bundle already exists” my further script didn’t execute(i.e ready, reload).

ABCpdf: How to run javascript after PDF-File is opened?

I have a component which generates PDF-File using ABCpdf. In that PDF-File I need a “DateTime Picker” field.
There are JavaScript functions which can be used for this purpose: AFDate_Format, AFDate_FormatEx (ABCpdf Documentation)

Thus, it can be achieved with simple JavaScript Code

getField("MyField").setAction("Format","AFDate_Format(6)");
getField("MyField").setAction("Keystroke", "AFDate_Format(6)");

I know how to add JavaScript events on fields in PDF-File (e.g. on mouse click). And it works. DateTime picker control is applied to the field when I click that control in a PDF-File.

But I need to apply DateTime picker control when PDF-File is opened.

According to PDF ISO (page 109) there is ‘JavaScript Dictionary’ which can be used for this, but it is not clear hot to add it using ABCPdf

How can I execute JavaScript code when PDF-File is loaded?

JS Path or Xpath syntax for dynamic webpage: Extracting tbody information

I am very new to JS,xpath and HTML but im trying to build a web scrubber for data mining purposes.
So far ChatGPT has been great help in getting what i need done but it seems to struggle with JS paths or xpath referencing.

How would i use CSS_SELECTOR to identify this element called LigandMainTable (refer to image) and its data listed within it? I basically want a script that would read the table data, extract the ligand name (first row), chain ID info (second row), ligand formula (third row), then download the .svg file that is linked in the 4th row (which would be the ligand 2D image).

I am not sure how to structure the syntax to properly extract the proper data type i need from these rows. screenshot of the website + html structure
If theres an efficient way to do this using a standard method, that would be greatly appreciated.

I’m having trouble with a second set of buttons/tabs, where when I click the other set of buttons it replaces the whole section the first set controls

I’m working on a commission right now and in the setup there’s two sets of buttons. One controls the like, main area, and in one of the tabs for the main area it shows a box meant to hold an image, and then an area to the side next to it that switches with tabs. For some reason, my second set of images causes the area to go blank, displaying nothing and removing the box. How do I fix this? Where did I go wrong?

Here’s my html, css, and javascript:

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" type="text/css"
        href="style.css">       
    </head>
<body>
    <div id="wrapper">

<!---TABS--->
        <div class="tab">
            <button class="tablinks" onclick="Tabs(event, 'profile')" id="defaultOpen">Profile</button>
            <button class="tablinks" onclick="Tabs(event, 'ref')">Ref Sheet</button>
          </div>

<div id="main">
<!---CONTENT--->
    <div id="content">
<!---PROFILE--->
        <div id="profile" class="tabcontent">
        <!---PROFILE IMAGE--->
            <div id="profileimage"></div>
        <!---PROFILE BUTTONS--->
            <div class="tab2" id="buttons2">
                <button class="tablinks" onclick="Tabs(event, 'about')" id="defaultOpen">About</button>
                <button class="tablinks" onclick="Tabs(event, 'extra')">Extra</button>
            </div>
        <!---ABOUT--->
                 <div id="about" class="tabcontent">hello</div>
        </div>
    <!---REF SHEET FT REFERENCES--->
        <div id="ref" class="tabcontent">
            <!---FLEX CONTAINER CONTAINING THE REFERENCES
            note: remove a div containing an <img src> to remove an image,
            copypaste a div containing an <img src> to add an image--->
            <div id="references" class="flex-container">
                <div class="box">
                    <!---IMAGE 1--->
                    <img src="https://t3.ftcdn.net/jpg/03/45/05/92/360_F_345059232_CPieT8RIWOUk4JqBkkWkIETYAkmz2b75.jpg">
                </div>
                <div class="box">
                    <!---IMAGE 2--->
                    <img src="https://t3.ftcdn.net/jpg/03/45/05/92/360_F_345059232_CPieT8RIWOUk4JqBkkWkIETYAkmz2b75.jpg">
                </div>
                <div class="box">
                    <!---IMAGE 3--->
                    <img src="https://t3.ftcdn.net/jpg/03/45/05/92/360_F_345059232_CPieT8RIWOUk4JqBkkWkIETYAkmz2b75.jpg">
                </div>
                <div class="box">
                    <!---IMAGE 4--->
                    <img src="https://t3.ftcdn.net/jpg/03/45/05/92/360_F_345059232_CPieT8RIWOUk4JqBkkWkIETYAkmz2b75.jpg">
                </div>
                <div class="box">
                    <!---IMAGE 5--->
                    <img src="https://t3.ftcdn.net/jpg/03/45/05/92/360_F_345059232_CPieT8RIWOUk4JqBkkWkIETYAkmz2b75.jpg">
                </div>
                <div class="box">
                    <!---IMAGE 6--->
                    <img src="https://t3.ftcdn.net/jpg/03/45/05/92/360_F_345059232_CPieT8RIWOUk4JqBkkWkIETYAkmz2b75.jpg">
                </div>
            </div>
        </div>
    </div>
</div> 
        
        </div>
<script src="javascript.js"></script>
            </body>
</html> 
#wrapper {
width:100%;
height:100%;  
display:inline-block;
}

#main {
color:red;
background-color:pink;
width:52%;
height:30rem;
margin-top:3rem;
margin-inline:auto;
border:6px solid;
border-color:brown;
border-radius:15% / 38px;
padding:4px;
}

#content {
color:rgb(0, 0, 0);
background-color:beige;
width:96%;
height:27rem;
position:relative;
top:1.4rem;
margin-inline:auto;
border:4.5px solid brown;
border-radius:15% / 30px;
overflow:auto;
scrollbar-width:none;
}

#profileimage {
background-color:pink;
width:16rem;
height:25rem;
border:2.5px solid brown;
border-radius:15% / 15px;
position:relative;
top:0.4rem;
}

#references {
color:red;
}

.flex-container {
display: flex;
flex-wrap:wrap;
margin: 0 auto;
  }

.box {
flex-grow:1;
flex-shrink:1;
flex-basis:calc(25% - 10px);
margin:5px;
}

img {
width:100%;
}

.tab {
position:relative;
text-align:center;
top:4.5rem;
}

.tab button {
background-color:burlywood;
padding:4px;
width:10rem;
font-size:1.8rem;
border:6px solid brown;
border-radius:10% / 8px;
cursor:pointer;
color:rgb(176, 103, 66);
}

.tab2 {
position:absolute;
text-align:center;
top:0.5rem;
left:22rem;    
}

.tab2 button {
background-color:burlywood;
width:8rem;
font-size:18px;
border:3.5px solid brown;
border-radius:10% / 8px;
cursor:pointer;
color:rgb(176, 103, 66);
    }

.tab button:hover {
background-color:rgb(191, 147, 89);
color:rgb(144, 58, 32);
border:6px solid brown;
border-radius:10% / 8px;
}
.tab button:active {
background-color:rgb(153, 73, 51);
color:rgb(70, 21, 6);
border:4px solid brown;
border-radius:10% / 8px;
}

.tabcontent {
display: none;
padding: 6px 12px;
border-top: none;
  }
function Tabs(evt, tabName) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
      tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
      tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(tabName).style.display = "block";
    evt.currentTarget.className += " active";
    
  } 

document.getElementById("defaultOpen").click();

I honestly have no clue what’s up with this. I tried messing with the naming conventions and altering the javascript very lightly a few times, but, admittedly I don’t know javascript much at all yet so there wasn’t much I knew to do. I’m guessing that I misplaced the tabs div in the html but I tried moving it around and it didn’t change anything at all. I’m so lost on this I’ve spent two days getting no work done because I just don’t know what’s going on with the issue.

How do I fix a child replacing its parent background when trying to add glowing border? [closed]

I am currently creating my portfolio and running into an annoying issue. I am attempting to add an animated border to my card within my container. The way the html is structured is I have a card within a container file that houses text as well as buttons. I am using ::before and ::after but it seems as though when adjusting the index of ::before and ::after to be behind the card itself it seems to replace its parents background entirely rather than adding the glowing affect behind it.

Here is the CSS code I can also attach HTML code if need be:

.container {
display: flex;
justify-content: space-around;
align-items: center;
padding-top: 4rem;
padding-bottom: 4rem;
padding-inline: 10px;
}
.container .main-text {
background: #313435;
max-width: 1000px;
padding-inline: 20px;
padding-top: 10px;
padding-bottom: 10px;
display: flex;
flex-direction: column;
border-radius: 10px;
position: relative;
z-index: 1;
}
.container .main-text::before,
.container .main-text::after {
content: "";
position: absolute;
inset: -15px;
z-index: -1;
background: conic-gradient(
    from var(--gradient-angle),
    #904E55,
    #97353e,
    #9b0c1a,
    #97353e,
    #904E55
);
border-radius: inherit;
animation: rotation 20s linear infinite;
}
.container .main-text::after {
filter: blur(30px);
}

Google Sheets App Script: Trigger on a copied sheet

I am trying to run a Google Sheets App Script whenever a checkbox is ticked.

  • Other users should be allowed to tick the checkbox.

When ticked, an App Script shows/hides different parts of the sheet.

  • This works fine for the owner of the sheet, but not for other users.

I would like to achieve the following workflow:

  1. User makes a copy of the entire Google Sheet
  2. User shares copy with colleagues
  3. App Script fires for user and colleagues

Things I have tried:

a. Simple Trigger DEMO

  • Using an onEdit Simple Trigger fails for other users due to “You are trying to edit a protected cell or object.”

b. Installable Trigger DEMO

  • Setting up an Installable Trigger allows other users to run the App Script.
  • However, manually setting up a trigger each time the sheet is copied can not reasonably be expected from users.

How would I want to trigger the App Script on a copied sheet?

Google Sheets App Script: Trigger for copied sheet

I am trying to run a Google Sheets App Script, whenever a checkbox is ticked.
Other users should be allowed to tick the checkbox.

When ticked, an App Script shows/hides different parts of the sheet.
This works fine for the owner of the sheet, but not for other users.

See the DEMO.

I would like to achieve the following workflow:

  1. User makes a copy of the entire Google Sheet
  2. User shares this copy with colleagues
  3. App Script fires for user and colleagues

Things I have tried:

  • Using an onEdit Simple Trigger fails due to permissions
  • Setting up an Installable Trigger allows other users to run the App Script.
  • However, manually setting up a trigger each time the sheet is copied can not reasonably be expected from users.

How would I want to programatically install a trigger, if none exists?

How to apply a script if url begins with [duplicate]

is it possible to apply a script to web pages only if the url begins with?
Right now in my website I use this, where I have ti manually insert each url where I want to hide the .title-shop:

<script>jQuery( document ).ready(function() {console.log( "ready!" );var hideUrl=    ['https://www.gustotosto.it/shop/aiadema/','https://www.gustotosto.it/shop/aromiinpiazza/',];if(hideUrl.indexOf(window.location.href)>=0){jQuery('.title-shop').hide();}});</script>

I’d like to modify the script so that all the .title-shop of the urls beginning with https://www.gustotosto.it/shop/ will be hidden.
Is it possible?

Frontend cannot make requests to backend

Here’s the translation into English:

Question:

I am working on an admin dashboard using React and Axios, but the frontend is not sending any requests to the backend at all. Nothing is displayed in the console or the network tab.

Code:

import React, { useEffect, useState } from "react";
import axios from "axios";

const AdminDashboard = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetchUsers();
  }, []);

  const fetchUsers = async () => {
    try {
      const response = await axios.get("/api/users");
      setUsers(response.data);
    } catch (error) {
      setError("ERROR");
    } finally {
      setLoading(false);
    }
  };

  if (loading) return <p>Loading users...</p>;
  if (error) return <p>{error}</p>;

  return <div>{/* ...Rendering Users... */}</div>;
};

export default AdminDashboard;

Backend:

// API route for users
app.get("/api/users", authenticateToken, (req, res) => {
  console.log("GOT API REQUEST: /api/users");
  db.query("SELECT id, first_name, last_name, email, is_active FROM users", (err, results) => {
    
    if (err) {
      console.error("Error retrieving users:", err);
      return res.status(500).json({ error: "Error retrieving users" });
    }

    console.log("Users retrieved successfully:", results);
    res.json(results); 
  });
});

Problem:

  • No requests to /api/users are being sent, and nothing is visible in the console or network tab.
  • The backend is running, and the URL is correct (http://localhost:3000/api/users).

I tried checking if Axios was imported correctly and verified that the backend was running. I expected that the frontend would successfully send a request to the backend and retrieve user data, which would then be displayed on the dashboard. However, no requests were sent at all, and I saw no errors or responses in the console or network tab.