window.location.href brings me to listing directory instead of page

I need help implementing window.location.href. I am trying to get to calculations.html from index.html by using window.location.href = “calculations.html”. However when I use this it always brings me to the listing directory.
So far I have tried

  • all the window.location and document.location methods (if I run window.location.href; just like that, it also brings me to the listing directory)
  • live server using local hosting and network hosting
  • I published my site on Netfly and got the same result
  • If I use an anchor with the same href it works, but I want to use JavaScript not HTML to do it.
  • I have refreshed my cache, disabled pop-ups, and checked my liveserver.settings.root and it is set to “”.
  • It is a small project, I have 2 html, 1 css, and 1 js. All are linked properly and in the same directory.

Here is my code from my script.js

function saveData() {
    /*eventually I want to save data here but for now 
     I'm just trying to get the page to change correctly */
    window.location.href = "calculations.html";
}

I am using VS Code with Five Server. I just started learning web dev a couple weeks ago so I’m still very new. Please help.

Automating clicks with userscript (tampermonkey)

I have a userscript for https://docs.google.com/forms. I’m trying to auto open the “Share” modal window and re assign all Editors to Responders.

To open the share modal this works:

function clickShareButton() {
    if (hasClickedShare) return;

    const interval = setInterval(() => {
        const shareButton = document.querySelector('div[role="button"][aria-label*="Share"]') ||
                            Array.from(document.querySelectorAll('button, div[role="button"]')).find(el => el.textContent.includes('Share'));

        if (shareButton) {
            shareButton.click();
            hasClickedShare = true;
            clearInterval(interval);
            console.log("Share button clicked!");

            // Wait 8 seconds to allow modal to fully load
            setTimeout(clickFirstEditorButtonInModal, 8000);
        } else {
            console.log("Share button not found, retrying...");
        }
    }, 1000);

    setTimeout(() => {
        clearInterval(interval);
        if (!hasClickedShare) {
            console.log("Stopped checking for Share button after 5 seconds.");
        }
    }, 5000);
}

After that I’m trying to click the Editor button and click the **

enter image description here
This is the html for the button:

<button class="mUIrbf-LgbsSe mUIrbf-LgbsSe-OWXEXe-Bz112c-UbuQg YzY9Wb X3Pm2e dxzMec-R6PoUb VfPpkd-ksKsZd-mWPk3d-OWXEXe-AHe6Kc-XpnDCe" jscontroller="O626Fe" jsaction="click:h5M12e; clickmod:h5M12e;pointerdown:FEiYhc;pointerup:mF5Elf;pointerenter:EX0mI;pointerleave:vpvbp;pointercancel:xyn4sd;contextmenu:xexox; focus:h06R8; blur:zjh6rb;mlnRJb:fLiPzd" data-idom-class="YzY9Wb X3Pm2e dxzMec-R6PoUb" jsname="dLruDf" aria-label="Editor. change permission" aria-expanded="false" aria-haspopup="menu" data-disable-idom="true" tabindex="-1" aria-describedby="c135"><span class="OiePBf-zPjgPe"></span><span class="RBHQF-ksKsZd" jscontroller="LBaJxb" jsname="m9ZlFb"></span><span jsname="Xr1QTb" class="mUIrbf-kBDsod-Rtc0Jf mUIrbf-kBDsod-Rtc0Jf-OWXEXe-M1Soyc"></span><span jsname="V67aGc" class="mUIrbf-vQzf8d">Editor</span><span jsname="UkTUqb" class="mUIrbf-kBDsod-Rtc0Jf mUIrbf-kBDsod-Rtc0Jf-OWXEXe-UbuQg"><span class="notranslate VfPpkd-kBDsod" aria-hidden="true"><svg width="24" height="24" viewBox="0 0 24 24" focusable="false" class="Q6yead QJZfhe mig17c "><path d="M7 10l5 5 5-5H7z"></path></svg></span></span></button>

I’m using this to try and click it:

function clickFirstEditorButtonInModal() {
    setTimeout(() => {
        const modal = document.querySelector('div[role="dialog"]') ||
                      document.querySelector('.VfPpkd-xl07Ob-XxIAqe') ||
                      document.querySelector('div[class*="modal"]');

        if (!modal) {
            console.log("Modal not found.");
            return;
        }
        console.log("Modal found:", modal);

        // Log all buttons in the modal for debugging
        const allButtons = modal.querySelectorAll('button');
        console.log(`Total buttons in modal: ${allButtons.length}`);
        allButtons.forEach((btn, index) => {
            console.log(`Button ${index}: text="${btn.textContent}", aria-label="${btn.getAttribute('aria-label')}"`);
        });

        let editorButton = modal.querySelector('button[aria-label*="Editor"]') ||
                           Array.from(allButtons).find(btn =>
                               btn.textContent.includes('Editor') && !btn.disabled
                           );

        if (editorButton) {
            editorButton.click();
            console.log("Editor button clicked:", editorButton);
            return;
        }

        console.log("Editor button not found, observing modal...");

        const observer = new MutationObserver((mutations, obs) => {
            let editorButton = modal.querySelector('button[aria-label*="Editor"]') ||
                               Array.from(modal.querySelectorAll('button')).find(btn =>
                                   btn.textContent.includes('Editor') && !btn.disabled
                               );

            if (editorButton) {
                editorButton.click();
                console.log("Editor button clicked via observer:", editorButton);
                obs.disconnect();
            }
        });

        observer.observe(modal, { childList: true, subtree: true });

        setTimeout(() => {
            observer.disconnect();
            console.log("Stopped observing modal after 5 seconds.");
        }, 5000);
    }, 3000); // 3s delay for UI to render
}

window.addEventListener('load', function() {
    console.log("Page loaded, starting script...");
    clickShareButton();
});

It doesn’t work. How do I go about this?

I cannot get firestore to work client-side to. Stuck on error: Uncaught TypeError: Failed to resolve module specifier “firebase/firestore”

I’ve followed the instructions for firebase. I can get it working with cloud functions no problem… but trying to be able to get documents from my firestore client-side without jumping through cloud-functions… I get stuck importing firestore.

Uncaught TypeError: Failed to resolve module specifier “firebase/firestore”. Relative references must start with either “/”, “./”, or “../”.

adding “/”, “./”, or “../” just hangs loading the javascript file with no error.

I’ve started completely fresh projects, and installed it using the correct methods described in the API. but this is where it gets stuck….

I’m jumping back into javascript after several years away, and relatively new to using terminal and NPM… but I’m 90% sure I’m doing it right… but there must be something i’m not understanding about the process, or maybe the capabilities…

I used to use firebase many years ago before Google bought it… and it was great for database management… i just don’t wan to have to jump through the cloud-function hoop in order to get and set documents… maybe that’s the only way?

How to add “” and “” before and after word on text area each line? [closed]

How to add word before and after sentence on each line in text area?

How to add "<div>" and "</div>" before and after words on text area each line?

<html>
<head>
    <style>
        .textarea {
            width: 100%;
            height: 30em;
            text-indent: 0.5em;
            margin-bottom: 20px;
        }
        .wrapper {
            text-align: right;
        }
    </style>
</head>
<body>

<textarea class="textarea">
line 1
line 2
line 3
</textarea>

<div class="wrapper">
<input type="submit" value="Add Text" onclick="addtext()" />
</div>

<script>
    function addtext(){
        .....
</script>

</body>
</html>

Thank you

How do I start learning node js [closed]

I am a Python programmer with experience in backend development and databases (Firebase, SQLite). I want to learn Node.js, but I struggle with focusing on a specific field.

Whenever I start learning, I find myself jumping between different topics (e.g., backend, real-time apps, automation) without making real progress.

What would be the best approach to learning Node.js in a structured way while ensuring I stay focused on a specific area? Are there any recommended projects or roadmaps for someone with a Python background?

Any advice on maintaining focus and avoiding distractions would be greatly appreciated.

Sync Google Calendar embedded with Google account

I have inserted Google Calendar embedded on my website using an iframe such as:

<iframe src="https://calendar.google.com/calendar/embed?src=<myEmail>.com&ctz=America%2FLos_Angeles"  frameborder="0" scrolling="no"></iframe> 

Everything works fine. However, to have a new event displayed on the calendar I have to refresh the page. Is there a way to have real-time updates on the iframe?

Thank you !

React Js fetch data from nested JSON API

I am trying to fetch data from an API, however it is throwing an error saying:

Uncaught runtime errors:
data.map is not a function
TypeError: data.map is not a function

enter image description here

  import React, { useEffect, useState } from 'react';

  const FetchNestedJson = () => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    fetch('https://my-api')
      .then((response) => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.json();
      })
      .then((jsonData) => {
        setData(jsonData);
        setLoading(false);
      })
      .catch((err) => {
        setError(err.message);
        setLoading(false);
      });
  }, []);

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

  return (
    <div>
      <h1>Users</h1>
      {data && data.map((user) => (
        <div key={user.list.id}>
          <p>{user.list.name}</p>
          <p>{user.list.ssid}</p> 
        </div>
      ))}
    </div>
  );
};

export default FetchNestedJson;

Any help would be much appreciated, thank you.

React Native FlatList not rendering latest input message from the websocket

I’m currently working on a real-time chat app in React Native (similar to WhatsApp or Instagram DMs) with a Django backend.

The issue I’m facing is that the latest message sent by the user via TextInput isn’t rendered on the screen. It does become visible when I refresh the screen but I want the message to appear immediately after the user presses the post button in real time just like how in WhatsApp you can see the message you just typed in the chat right after hitting send.

// Messages for the conversation
const [messages, setMessages] = useState([]);

// Text input
const [msg, setMSG] = useState('');

useEffect(() => {
    const socket = new WebSocket(`ws://XXXX/ws/chat/${conversationId}/`);
    socketRef.current = socket;

    socket.onopen = () => {
       console.log(`Connected to chat room ${conversationId}`);
    }

    socket.onmessage = (event) => {
       const data = JSON.parse(event.data);
       setMessages((prevMessages) => [...prevMessages, data]);
    };

    socket.onclose = () => {
       console.log("Websocket closed");
    };
     return () => {
       socket.close();
   };
}, [conversationId]);

// sendMessage function which either takes a text message or media and sends it via the websocket
const sendMessage = (text = msg, mediaUrl = null) => {
   if (!text && !mediaUrl) return;
   const cleanMediaUrl = mediaUrl ? decodeURIComponent(mediaUrl).replace(/^/+/, '') : null;

   const messageData = {
      sender: user.username,
      message: text || "",
      media: cleanMediaUrl
   };
   if (socketRef.current && socketRef.current.readyState === WebSocket.OPEN) {
      socketRef.current.send(JSON.stringify(messageData));
   } else {
      alert("Websocket is not open");
   }
   setMSG('');
};

// Renders the data in the messages state
<FlatList
  data={messages}
  extraData={messages}
  keyExtractor={(item, index) => index.toString()} 
  inverted
  renderItem={({ item }) => (...)}
/>

// The post button which sends the typed in message from TextInput to the sendMessage function
<TouchableOpacity onPress={() => sendMessage(msg)} style={styles.postButton}>
   <Text style={{justifyContent: 'center', alignSelf: 'center', color: 'white'}}>POST</Text>
</TouchableOpacity>

I added ‘extraData’ into the FlatList to try and force a re-render but it doesn’t fix the issue.

The websocket itself is fine as when I click POST it creates the message in my backend and appears when I refresh the screen. My problem is the most recent message doesn’t render in real time after it’s been typed and sent.

Note: I left out some of the non-relevant parts in the file to avoid making it too lengthy.

How to do loopings/loops in “Delivery Fleet Optimization with GIS Tutorial” video?

I am following the “Delivery Fleet Optimization with GIS” Tutorial from AnyLogic to help be the backbone of my simulation for visiting well locations. After the “unpacking” delay block, I need to have a select output where the truck would then go back to the “packing” delay block and back through the system. I’ve tried using a release, move to, seize block, and a connector back to the “packing” delay to have a loop. Below, I’ve included a 2D model without GIS that I’m trying to recreate. enter image description here

Browser using JS to record audio, how to prevent recording all the system audio?

I am using Recorder.js to record microphone input from browser.

The current version can prevent recording audio from browser (with very very minor loopback) but still recording audio (Full volume) from outside of the browser.

When I use navigator.mediaDevices.getUserMedia(), I already specify a specific audioinput (microphone), then it does prevent recording audio from Browser (play audio from browser), but, when play audio from other application outside of browser, it still capture that audio.

Why this can prevent recording browser audio but still capture other audio outside of the browser?

How can I improve to prevent record all system audio?

I know that on some meeting application (like Microsoft Team), I have an option to enable/disable sending system audio which I can opt to not record system audio and that is working (not capture any system audio). Probably on native application I can have that option to do but using JS on browser can not?

Committing changes on GitHub will cause Railway to redeploy, won’t update the final JS output in a private network

I have a JavaScript repository which is to make a website. This repo has been successfully connected to Railway – Railway automatically redeploys whenever I commit changes to the repo.

The problem lies with the output, as it never updates on the web page. No matter what changes I make on GitHub (and consequently what is redeployed on Railway), the output in the web pages doesn’t change.

When I switched the repo to a public network, the changes showed up, but the database wouldn’t connect; it outputted this error: {“error”:”connect ECONNREFUSED ::1:3306″}.

I’ve tried everything but I can’t seem to update the webpages so that there’s new output.

I’m also unsure as to whether I should be using a private or public network to develop the website.

The following code is part of the repo on GitHub. Ideally, I want to print out “Hello Max” using the greet function, onto the private network web page (that passes through my Railway project).
Understanding how to do this should fix my problem:

// imports
import express from "express";
import cors from "cors";
import db from "./db.js";

const app = express();

// defining the app
app.use(cors());
app.use(express.json());

// lets me know the API is running
app.get("/", (req, res) => {
  res.send("Farm Management API is running...");
});

// What I want to print out
import { greet } from "./index.js"; // imports the function from another js file

//https://tsedatabasedevelopmentproduction.up.railway.app/users is the webpage I want to show the greeting
app.get("/users", async (req, res) => { 

  try {
    console.log(greet("Max"));
    res.json({ message: greet("Max") });

  } catch (err) {
    console.error(err);
    res.status(500).json({ error: err.message });
  }
});

How to remove null rows from items array sent by Spotify API [duplicate]

I’m trying to implement an autocomplete feature to get suggestions of playlists from the Spotify API. I’m able to connect and get a response from Spotify, but some of the rows in their response are sometimes null and that makes things break. Is it possible to delete those null rows before attempting to map the results?

The error that I sometimes get says: Cannot read properties of null (reading ‘name’). If I validate for ‘name’, then I get the same error for ‘images’ or ‘owner’. So I might as well just get rid of the whole null row, but I’m not sure how to do that.

I’m using the necessary scopes, according to documentation:

$options = [
    'scope' => [
      'user-read-email',
      'user-read-private',
      'user-read-recently-played',
      'user-library-modify',
      'playlist-read-private',
      'playlist-read-collaborative',
      'playlist-modify-private',
      'playlist-modify-public',
      'user-follow-modify',
    ],
    'state' => $state,
];

This is my script:

<script>
// Autocomplete for playlist lookup (step 1 of form)
$(function() {
  $("#playlist-link").autocomplete({
    source: function(request, response) {
      // Replace with your Spotify API access token
      const accessToken = "<?php echo $_SESSION['access_token'] ?>";

      $.ajax({
        url: "https://api.spotify.com/v1/search",
        headers: {
          "Authorization": "Bearer " + accessToken
        },
        data: {
          q: request.term,
          type: "playlist",
          limit: 10 // Adjust the number of results as needed
        },
        success: function(data) {
          // Can I delete the 'items' rows that are null here? If so, how??
          if (data.playlists && data.playlists.items) {
            const playlists = data.playlists.items.map(function(playlist) {
            return {
                label: playlist.name, // Displayed in the autocomplete list
                value: playlist.name, // Value inserted into the input field
                id: playlist.id, // Store the playlist ID for later use
                images: playlist.images, // store images for display
                owner: playlist.owner.display_name // store owner name
            };
            });
            response(playlists);
          } else {
            response([]); // Return an empty array if no results are found
          }
        },
        error: function(xhr, status, error) {
          console.error("Spotify API error:", error);
          response([]); // Handle errors gracefully
        }
      });
    },
    minLength: 3, // Start searching after 3 characters
    select: function(event, ui) {
      // Handle the selected playlist (e.g., store the ID)
      console.log("Selected playlist ID:", ui.item.id);
      // You can store the playlist ID in a hidden field or use it directly
      $("#playlist-id").val(ui.item.id); // Example: storing in a hidden input
    },
    open: function() {
      // Style the dropdown list (optional)
      $(".ui-autocomplete").css("z-index", 1000); // Ensure it's on top
    },
    focus: function(event, ui) {
      // Prevent the default behavior (inserting the value on focus)
      event.preventDefault();
    }
  }).autocomplete("instance")._renderItem = function(ul, item) {
    // Custom rendering of each item in the dropdown
    const image = item.images && item.images.length > 0 ? item.images[0].url : "placeholder.jpg"; // Use a placeholder if no image
    return $("<li>")
      .append(
        "<div>" +
        "<img src='" + image + "' style='width: 50px; height: 50px; margin-right: 10px; vertical-align: middle;'/>" +
        "<span style='vertical-align: middle;'>" + item.label + "</span>" +
          "<br> <span style='font-size: 12px; color: grey; vertical-align: middle;'>By: " + item.owner + "</span>" +
        "</div>"
      )
      .appendTo(ul);
  };
});

</script>

And this is what I see in the console:

Screenshot of Chrome console

I’m trying AWS Transcribe streaming service and it does not work. What’s wrong with my code?

I’m recording an audio file, I convert it to a format accepted by AWS Transcribe and I pass it to the trascribe service. The error is this:

TypeError: e.$unknown is undefined
visit models_0.js:21
fn Aws_restJson1.js:343
asyncIterator SmithyMessageEncoderStream.js:10
domande_generiche.html:107:29

Here’s the code of my javascript

    import { TranscribeStreamingClient, StartStreamTranscriptionCommand } from "https://cdn.jsdelivr.net/npm/@aws-sdk/client-transcribe-streaming@latest/+esm";
    let mediaRecorder;
    let audioChunks = [];

    const transcribeClient = new TranscribeStreamingClient({
        region: "us-east-1",
        credentials: {
            accessKeyId: "xxxxxx",
            secretAccessKey: "xxxxxx"
        }
    });

    document.addEventListener("click", async function(event) {

        if (event.target.tagName === "BUTTON" && event.target.hasAttribute("data-domanda")) {
            let bottone = event.target;
            let numeroDomanda = bottone.getAttribute("data-domanda");
            console.log("Hai premuto il pulsante della domanda:", numeroDomanda);

            try {
                const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                mediaRecorder = new MediaRecorder(stream, { mimeType: "audio/webm" });
                audioChunks = [];

                mediaRecorder.ondataavailable = event => {
                    if (event.data.size > 0) {
                        audioChunks.push(event.data);
                    }
                };

                mediaRecorder.onstop = async () => {
                    const audioBlob = new Blob(audioChunks, { type: "audio/webm" });
                    const audioFile = new File([audioBlob], "recording.webm", { type: "audio/webm" });
                    console.log("File audio registrato", audioFile);
                    
                    
                    try { //errore in questo try
                    
                        const audioBuffer = await audioFile.arrayBuffer();
                        const audioUint8 = new Uint8Array(audioBuffer);
                        
                        // Invia l'audio per la trascrizione streaming
                        const audioStream = new ReadableStream({
                            start(controller) {
                                controller.enqueue(audioUint8);
                                controller.close();
                            }
                        });

                        
                        const command = new StartStreamTranscriptionCommand({
                            LanguageCode: "it-IT",
                            MediaSampleRateHertz: 16000,  // Cambiato per adattarsi a AWS
                            MediaEncoding: "pcm",
                            AudioStream: audioStream
                        });
                        
                        
                        const response = await transcribeClient.send(command);
                        let transcription = "";

                        if (response?.TranscriptResultStream) {
                        
                            for await (const event of response.TranscriptResultStream) {
                                if (event.TranscriptEvent && event.TranscriptEvent.Transcript) {
                                    const results = event.TranscriptEvent.Transcript.Results;
                                    if (results?.length > 0 && results[0].Alternatives?.length > 0) {
                                        transcription += results[0].Alternatives[0].Transcript + " ";
                                    }
                                }
                            }
                            
                        } else {
                            console.error("TranscriptResultStream non disponibile", response);
                        }

                        console.log("Trascrizione:", transcription.trim());
                        alert("Trascrizione: " + transcription.trim());
                    } catch (err) {
                    
                        console.error("Errore durante la trascrizione:", err);
                    }

                    // Reset bottone
                    bottone.textContent = "Rispondi";
                    bottone.classList.remove("registrando");
                };

                mediaRecorder.start();
                bottone.textContent = "Stop";
                bottone.classList.add("registrando");

                bottone.addEventListener("click", () => {
                    if (mediaRecorder.state === "recording") {
                        mediaRecorder.stop();
                        stream.getTracks().forEach(track => track.stop());
                    }
                }, { once: true });
            } catch (error) {
                console.error("Errore durante il processo:", error);
                alert("Errore durante il processo.");
            }
        }
    });

How to type the parameters of a parameterized function call?

In many instances I follow the following pattern, where types like Bike and Train are both Vehicles, and there is a map providing a helper function for each. Everything passes TypeScript typing, and the JavaScript runs correctly. But linters complain (in my case BiomeJS).

Specifically, in printOut, when we cast v as any, most linters don’t like using any. But there’s no obvious cast that fixes the types.

Casting x as never does appear to work, but seems quite counterintuitive (How is this object a never? Why does my linter even allow me to cast to a never?). Obviously, I could ignore the error, but I’d rather either find a better way to type my JavaScript code without changing it, or find a better pattern that types nicely.

type Bike = {
    type: "bike";
    gears: number;
};

type Train = {
    type: "train";
    cars: number;
};

type Vehicle = Bike | Train;

type VehicleType = Vehicle["type"];

const vehicleMap: {
    [K in VehicleType]: (x: Extract<Vehicle, { type: K }>) => void;
} = {
    bike: (x: Bike) => {
        console.log(x.gears);
    },
    train: (x: Train) => {
        console.log(x.cars);
    },
};

const printOut = (v: Vehicle): void => {
    vehicleMap[v.type](v as any);
};

P.S. I suppose classes could work to resolve this, by making these instance methods, but I’d rather not need to add classes to what I thought was a simple object pattern. And, besides, classes add the chance to subclass and override, while I don’t want this behavior overridable. This would be quite a change in implementation, just to allow me to type what was otherwise perfectly behaving JavaScript.

full Calendar 6.1.15 timeslots are not showing in week view

What i need to show is this on switching from day to week view
[![enter image description here][1]][1]

but what i’m getting is following
[![enter image description here][2]][2]

Following is my switching code

if (window.myCalendar && document.getElementById('calendar')) { 
            console.log("FullCalendar instance found:", window.myCalendar);

            // Remove all events
            window.myCalendar.getEvents().forEach(event => event.remove());
            // Add new event source
            window.myCalendar.addEventSource(myEvents);
            window.myCalendar.setOption('defaultTimedEventDuration', '01:00:00');
            window.myCalendar.setOption('forceEventDuration', true);
            window.myCalendar.setOption('slotMinTime', '00:00:00');
            window.myCalendar.setOption('slotMaxTime', '23:00:00');
            window.myCalendar.setOption('contentHeight', 'auto');
            window.myCalendar.setOption('allDaySlot', false); // Hide all-day
            // Rerender the calendar to reflect the changes
            //window.myCalendar.refetchEvents();
           // window.myCalendar.render();
            document.getElementById('calendar').style.display = 'block'; // Ensure calendar is visible

            setTimeout(() => {
                window.myCalendar.addEventSource(myEvents);

  
                window.myCalendar.refetchEvents();
    
                window.myCalendar.changeView("timeGridWeek"); // Ensure it stays in week view
            }, 300); // Small delay to allow events to update


        } else {
            console.error("FullCalendar instance not found!");
        }

myEvents has end null & i can create any end. What i’m doing wrong
[1]: https://i.sstatic.net/LL1fIxdr.png
[2]: https://i.sstatic.net/3sm7belD.png