Background video loop seamless in Firefox but not Chrome?

I have a website that I have been working on that has a responsive background video. How it is supposed to work:

  1. Detect the screen size of the device (mobile screen vs. larger “desktop” screen)
  2. Preload the correct video on the blank htmtl background video element
  3. Quickly & gently fade the video element in once it loads
  4. Loop the video indefinitely, with no further fading or sharp transitions
  5. Monitor for screen size changes and reload a different video if necessary
document.addEventListener('DOMContentLoaded', function() {
    var vid = document.querySelector('video'); // Adjust this selector to target your video element specifically.
    var mobileReload = 0;
    var initialLoad = 0;

    function updateVideoSource() {
        if (window.innerWidth <= 768 && mobileReload == 0) {
            vid.classList.remove('is-loaded'); // Remove class before setting the correct source
            mobileReload = 1;
            vid.src = '/wp-content/uploads/2024/04/Homepage-Video-Mobile.webm'; // Add your mobile video path here.
            vid.removeAttribute("loop");
            vid.classList.add('is-loaded'); // Add class after setting the correct source
            if (initialLoad == 0) {
                initialLoad = 1;
                vid.style.opacity = 0;
                vid.oncanplaythrough = function() {
                    setTimeout(function() {
                        fade(vid);
                    }, 0.01);
                };
            }
        }
        if (window.innerWidth > 768) {
            vid.classList.remove('is-loaded'); // Remove class before setting the correct source
            mobileReload = 0;
            vid.src = '/wp-content/uploads/2024/04/Homepage-Video-Desktop.webm'; // Add your default video path here.
            vid.removeAttribute("loop");
            vid.classList.add('is-loaded'); // Add class after setting the correct source
            if (initialLoad == 0) {
                initialLoad = 1;
                vid.style.opacity = 0;
                vid.oncanplaythrough = function() {
                    setTimeout(function() {
                        fade(vid);
                    }, 0.01);
                };
            }
        } else {
            // No update to avoid reloading when scrolling on mobile due to address bar resizing
        }
    }

    function fade(element) {
        var op = 0;
        var timer = setInterval(function() {
            if (op >= 1) clearInterval(timer);
            element.style.opacity = op;
            element.style.filter = 'alpha(opacity=' + op * 100 + ")";
            op += op * 0.1 || 0.1;
        }, 10);
    }
    // Add event listener for the 'ended' event to loop the video
    vid.addEventListener('ended', function() {
        vid.currentTime = 0; // Reset video to beginning
              vid.play();
    });

    window.addEventListener('resize', updateVideoSource);
    updateVideoSource(); // Call it on initial load as well.
});

The problem I am having is with Step 4. The loop works perfectly on the browser I use, develop, and test on (Firefox, and iOS Safari). But most consumers afaik use Chrome and there is an ugly gray fade stutter for about half a second on Chrome when the video loops. Both videos are .WEBM and < 3mb. Any ideas?

As you can see I’m trying a couple of different things to fix it but neither are working.

I read that some browsers handle loops differently so I started by removing the loop attribute from the video. I know it would be easier to do that in the actual HTML but I’m kind of cheating and using a WP Cover Block as the video bg element and manipulating it with JS so this is just easier. Than I add an event listener to manually detect when the video ends and restart it. This doesn’t work- as in, it works exactly the same as having the loop attribute in the html and doesn’t fix the issue.

I also added the variable initialLoad to prevent the fade event from running more than once, that isn’t working either, so I’m assuming it’s something to do with Chrome here.

How can I terminate a function process when an event occurred

everyone, there is a task, where I need to terminate a function process when an event occurs.

Normally, when throwing an error in anything inside the process, for example, throwing an error from the delay in any step of the next steps, the process will terminate without any problems.

But if I created an event listener, that’s responsible for terminating the process. If I make throw error inside it the process will keep running without any problems in the process. and it will be considered as an Unhandled Rejection or DOMException.

  • Because the error thrown was made inside the listener context and not the main function context everything will keep going without any problems so to make it clear I will explain what I mean with some examples

  • In The first example I’m tring to terminate the process within the event listener, but the process will continue normally without problems and it is treated as an Unhandled Rejection or DOMException

(() => {
  class EventEmitter {
    constructor() {
      this.events = {};
    }

    on(event, listener) {
      if (!this.events[event]) {
        this.events[event] = [];
      }

      this.events[event].push(listener);

      // Return a function that can be used to remove this specific listener
      return () => {
        this.off(event, listener);
      };
    }

    emit(event, ...args) {
      if (this.events[event]) {
        this.events[event].forEach(listener => listener(...args));
      }
    }

    removeListeners(event) {
      delete this.events[event];
    }

    off(event, listener) {
      if (this.events[event]) {
        this.events[event] = this.events[event].filter(existingListener => existingListener !== listener);
      }
    }
  }

  const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
  const processEmitter = new EventEmitter();

  async function startProcess(params) {
    try {
      const removeListener = processEmitter.on('stop', async () => {
        removeListener(); 
        throw new Error(`Process stopped due to external event`); 
      });

      await delay(2000);
      console.log('finished step 1');
      await delay(2000);
      console.log('finished step 2');
      await delay(2000);
      console.log('finished step 3');
      await delay(2000);
      console.log('finished step 4');
      await delay(2000);
      console.log('finished step 5');
      await delay(2000);
      console.log('finished step 6');
    } catch (err) {
      console.log('Process terminated:', err.message);
    } finally {
      console.log('done !!')
    }
  }

  startProcess();

  setTimeout(() => {
    processEmitter.emit('stop');
  }, 5000);
})();

  • In The following example I’m trying to throw the error with proxy when the value changed
(() =>  {
  const processEmitter = new EventEmitter();
  async function startProcess(params) {
    try {
      // use proxy as a middleware when the value change
      const abortHandler = new Proxy({ msg: '' }, {
        set(target, key, value) {
          target[key] = value;
          throw new Error(value);
        }
      });

      const removeListener = processEmitter.on('stop', async () => {
        removeListener(); 
        abortHandler.msg = `Process stopped due to external event`; 
      });

      await delay(2000);
      console.log('finished step 1');
      await delay(2000);
      console.log('finished step 2');
      await delay(2000);
      console.log('finished step 3');
      await delay(2000);
      console.log('finished step 4');
      await delay(2000);
      console.log('finished step 5');
      await delay(2000);
      console.log('finished step 6');
    } catch (err) {
      console.log('Process terminated:', err.message);
    } finally {
      console.log('done !!')
    }
  }

  startProcess();

  setTimeout(() => {
    processEmitter.emit('stop');
  }, 5000);
})();
  • In the following example I’m trying to terminate the process with function that will throw the error when called but also it doesn’t work because it’s running inside the listener context not at the main function context
(() =>  {
  const processEmitter = new EventEmitter();
  async function startProcess(params) {
    try {
      // use proxy as a middleware when the value change
      const reject = msg => {
        throw new Error(msg);
      } 

      const removeListener = processEmitter.on('stop', async () => {
        removeListener(); 
        reject(`Process stopped due to external event`); 
      });

      await delay(2000);
      console.log('finished step 1');
      await delay(2000);
      console.log('finished step 2');
      await delay(2000);
      console.log('finished step 3');
      await delay(2000);
      console.log('finished step 4');
      await delay(2000);
      console.log('finished step 5');
      await delay(2000);
      console.log('finished step 6');
    } catch (err) {
      console.log('Process terminated:', err.message);
    } finally {
      console.log('done !!')
    }
  }

  startProcess();

  setTimeout(() => {
    processEmitter.emit('stop');
  }, 5000);
})();
  • I also tried to wrap the whole function in a Promise and use reject with hope to stop the process when call reject but because of the Promise sync nature the process will keep going after calling reject without any problems
(() => {
  const processEmitter = new EventEmitter();
  async function startProcess(params) {
    return new Promise(async (_resolve, reject) => {
      try {
        const removeListener = processEmitter.on('stop', async () => {
          removeListener();
          reject(`Process stopped due to external event`);
        });

        await delay(2000);
        console.log('finished step 1');
        await delay(2000);
        console.log('finished step 2');
        await delay(2000);
        console.log('finished step 3');
        await delay(2000);
        console.log('finished step 4');
        await delay(2000);
        console.log('finished step 5');
        await delay(2000);
        console.log('finished step 6');
      } catch (err) {
        console.log('Process terminated:', err.message);
      } finally {
        console.log('done !!')
      }
    })
  }

  startProcess();

  setTimeout(() => {
    processEmitter.emit('stop');
  }, 5000);
})();

  • I also tried intervals but the result is still the same because throwing the error will be within the callback context not at the main function context

  • The solution I found is a repetitive solution, which is the normal case, but I need to reduce repeating the same steps / code more than once, which is to use a variable or AbortController. However, these solutions will also be invalid, and it is not the best solution, because when I make a call to controller.abort() Also, step 3 is executed even though it is not supposed to be executed, because the stop event is called in the first second of the function call, meaning that step 3 is executed while it’s suppose to not, and after that it goes to step 4 and wow it findout that signal is aborted, so it throws an error + that this step has a lot of repeativitive code, meaning that If each delay represents a function alone with different code, then repeat the same step for all of them

(() =>  {
  const delay = (ms, signal) => {
    if (signal?.aborted) {
      throw new Error(signal?.reason || 'Aborted')
    }

    return new Promise(resolve => setTimeout(resolve, ms))
  };

  const processEmitter = new EventEmitter();
  const controller = new AbortController();
  const { signal } = controller;

  async function startProcess(params) {
    try {
      const removeListener = processEmitter.on('stop', async () => {
        removeListener();
        controller.abort('Process stopped due to external event');
      });

      await delay(2000, signal);
      console.log('finished step 1');
      await delay(2000, signal);
      console.log('finished step 2');
      await delay(2000, signal);
      console.log('finished step 3');
      await delay(2000, signal);
      console.log('finished step 4');
      await delay(2000, signal);
      console.log('finished step 5');
      await delay(2000, signal);
      console.log('finished step 6');
    } catch (err) {
      console.log('Process terminated:', err.message);
    } finally {
      console.log('done !!')
    }
  }

  startProcess();

  setTimeout(() => {
    processEmitter.emit('stop');
  }, 5000);
})();
  • The last solution is variable, which is also the same idea as aborted signals, but the difference is that abort controller signals make the application logic better and more elegant, and you can use it in differnt ways.
(() =>  {
  const delay = (ms, err) => {
    if (err) {
      throw err;
    }

    return new Promise(resolve => setTimeout(resolve, ms))
  };

  const processEmitter = new EventEmitter();

  async function startProcess(params) {
    try {
      let err = null;
      const removeListener = processEmitter.on('stop', async () => {
        removeListener();
        err = new Error('Process stopped due to external event');
      });

      await delay(2000, err);
      console.log('finished step 1');
      await delay(2000, err);
      console.log('finished step 2');
      await delay(2000, err);
      console.log('finished step 3');
      await delay(2000, err);
      console.log('finished step 4');
      await delay(2000, err);
      console.log('finished step 5');
      await delay(2000, err);
      console.log('finished step 6');
    } catch (err) {
      console.log('Process terminated:', err.message);
    } finally {
      console.log('done !!')
    }
  }

  startProcess();

  setTimeout(() => {
    processEmitter.emit('stop');
  }, 5000);
})();

How to have an app window not take away focus like in Windows 11 emoji app

Let’s say you have Notepad open in Windows 11. You hit Win+. shortcut to open the emoji app. Click on an item and it pastes it in wherever your | symbol is in your Notepad.

Essentially we have a window we can control like any normal piece of UI, without removing focus from the previously focused window (Notepad in our case).

How would I be able to replicate this behavior in Electron?

enter image description here

Extra note:
This is something that could potentially be achieved by making the app window unfocusable and adding in a bunch of code that would process global inputs, but that would result in quite an overengineered solution. I’m curious if there’s anything out of the box that would support this behavior.

Any help much appreciated!

Hide the button if value of variable is missing

I am a novice in Javascript and I have a variable inside a for loop like below:

myTBody2 += `
<tr><td><button class="btn btn-sm btn-primary" onclick="myFetcher('${data._links.first.href}')">First</button></td>
  <td><button class="btn btn-sm btn-primary" onclick="myFetcher('${data._links.self.href}')">Current</button></td>
  <td><button class="btn btn-sm btn-primary" onclick="myFetcher('${data._links.next.href}')">Next</button> </td>
  <td><button class="btn btn-sm btn-primary" onclick="myFetcher('${data._links.last.href}')">Last </button></td>
</tr>`;

Now, say, if the value of ${data._links.next.href} is undefined or missing, how do I hide it?
Is there a javascript (vanilla JS) inline (one liner) function available to do that?
Any pseudo/pointers/solution will be greatly appreciated.

v-data-table showing up as empty despite items being in the backing array

I have this function fetchItemData that fetches data from the DB and assigns it to itemsList, which is bound to items of v-data-table. The v-data-table shows the new data perfectly fine on other events, like a change in sort parameters or items-per-page. But when searchText changes (@input event on v-text-field), despite the data being returned perfectly fine and assigned to itemsList with no problems, it does not show up in the table at all and I get the no-data screen.

Even when I added a debug function printItems that simply ran console.log(this.itemsList) upon the table being clicked, it shows that the itemsList = a list of items matching the search query. They’re just not being shown.

I have a reduced version of my code here with extraneous things removed:

Template:

<template>
  <v-card class="pa-4">
    <v-data-table
      v-model="selected"
      v-model:sort-by="sortBy"
      v-model:items-per-page="itemsPerPage"
      v-model:page="pageNum"
      :search="searchText"
      :headers="headers"
      :items="itemsList"
      :loading="itemsLoading"
      :pageText="allFetched ? '{0}-{1} of {2}' : '{0}-{1} of more'"
      :last-icon="allFetched ? '$last' : ''"
      @update:itemsPerPage="fetchItemData"
      @update:sortBy="fetchItemData"
      @update:page="fetchNextPage"
      item-key="id">
      <template v-slot:top>
        <v-container fluid>
          <v-row class="pb-2">
            <v-text-field
              v-model="searchText"
              label="Search"
              prepend-inner-icon="mdi-magnify"
              bg-color="transparent"
              variant="underlined"
              density="compact"
              single-line
              hide-details
              clearable
              @input="fetchItemData" />
            <v-btn
              v-if="selected && selected.length"
              @click="() => {}"
              color="error"
              size="small"
              class="ml-4 float-right align-self-end">
              Delete Selected
            </v-btn>
          </v-row>
        </v-container>
      </template>

      <template v-slot:loading>
        <v-skeleton-loader type="table-tbody" />
      </template>

      <template v-slot:no-data>
        <div class="mt-6 text-subtitle-1">No data found</div>
        <v-btn
          class="mt-2 mb-6"
          color="primary"
          size="small"
          variant="flat"
          prepend-icon="mdi-refresh"
          @click="fetchItemData"> // <- the problem
          Retry
        </v-btn>
      </template>

      templates for item rows etc...
    </v-data-table>
  </v-card>
</template>

Script:

import { items } from '@/services/items.js'

export default {
  data: () => ({
    itemsList: [],
    itemsLoading: false,
    itemsPerPage: 10,
    pageNum: 1,
    searchText: '',
    selected: [],
    sortBy: [{ key: 'updatedAt', order: 'desc' }],
    allFetched: false
  }),
  methods: {
    fetchItemData() {
      var numToFetch = this.itemsPerPage + 1 //get one extra so next button remains active if there exist items past curr page

      var searchParams = {
        query: this.searchText
      }

      var pageParams = {
        size: numToFetch,
        sort: this.sortBy[0]
      }

      this.itemsLoading = true
      items
        .list(searchParams, pageParams)
        .then((response) => {
          if (response.data) {
            this.itemsList = response.data?.items || []
          } else {
            this.itemsList = []
          }

          //if items received is less than num to fetch, we've reached end
          if (response.data?.items && response.data.items.length < numToFetch)
            this.allFetched = true

          this.itemsLoading = false
          return this.itemsList
        })
        .catch(() => {
          this.itemsList = []
          this.itemsLoading = false
        })
    },
    fetchNextPage() {...}
  computed: {
    headers() {
      return [
        row headers...
      ]
    }
  },
  created() {
    this.fetchItemData()
  },
  name: 'ItemsTable'
}

Any help would be much appreciated: thank you!

Angular material table multiple header rows mapping

There is a sample of data table which consists of multiple header rows

|          |  Song 1        | Song 2         | Song 3         |
|---------------------------|----------------|----------------|
|  Artist  | Perc % | Val $ | Perc % | Val $ | Perc % | Val $ |
|-------------------------------------------------------------|
| Q1       | 10%    | 200$  | 15%    | 250$  |        |       |  
| BW       | 10%    | 200$  | 10%    | 200$  |        |       |
| POD      |  5%    | 150$  | 10$    | 200$  |        |       |
|          |        |       |        |       |        |       |
| SUM      | 25%    | 550$  | 25%    | 650$  |        |       |


with provided dataset

{
    "data": [{
            "artistId": "A001",
            "artistName": "Q1",
            "songs": [{
                    "songId": "S001",
                    "songName": "Song 1",
                    "percentage": "10%",
                    "value": "$200"
                },
                {
                    "songId": "S002",
                    "songName": "Song 2",
                    "percentage": "15%",
                    "value": "$250"
                }
            ]
        },
        {
            "artistId": "A002",
            "artistName": "BW",
            "songs": [{
                    "songId": "S001",
                    "songName": "Song 1",
                    "percentage": "10%",
                    "value": "$200"
                },
                {
                    "songId": "S002",
                    "songName": "Song 2",
                    "percentage": "10%",
                    "value": "$200"
                }
            ]
        },
        {
            "artistId": "A003",
            "artistName": "POD",
            "songs": [{
                    "songId": "S001",
                    "songName": "Song 1",
                    "percentage": "5%",
                    "value": "$150"
                },
                {
                    "songId": "S002",
                    "songName": "Song 2",
                    "percentage": "10%",
                    "value": "$200"
                }
            ]
        }
    ],
    "summary": [{
            "songName": "Song 1",
            "totalPercentage": "25%",
            "totalValue": "$550"
        },
        {
            "songName": "Song 2",
            "totalPercentage": "25%",
            "totalValue": "$650"
        }
    ]
}

I’m wondering could provided dataset be mapped in order to get something like on the sample table using angular material table? There is no need for pagination.

Download HTML content as page.html rendered in a VueJS preview

I have developed a VueJS-based application for front-end content management.
I’m seeking to integrate a ‘download’ button functionality within the application. This feature will enable the users to download the previewed and edited content as an HTML file. Additionally, I aim to implement a mechanism to exclude specific div elements from being included in the downloaded file.

I have a script.js where I have all the methods, default.html where I have the navigation bar and where the button download should be listed, and finally, preview.html where the content is called and have my v__preview div that I need to export

SVG editor weird scrolling bug

Weird scrolling behavior on dragging Foreign object.
so i want to build a moodboard application in vue. Sort of like https://mydraft.cc/ where a user can have a board where he can drag certain parts of the page. I see that many applications use SVG for this. In the board users will have specific micro applications that needs extensive reactivty. There for i am using foreign objects inside of the svg.

Now its all working great except for one weird scroll behavior. as included in the added video when i drag the element down at first its working perfectly. But when i scroll down and then i drag the red square the svg scrolls down instead of only dragging the box itself down. How do i prevent the browser from scrolling and only move the box down.

if you want to see the weird behavior i recorded it here. https://www.loom.com/share/f5c7f473d0c841d692fa759c62ba4203?sid=89fedaa6-0b07-4561-a0bd-b1ef1d1f737c

At the top and bottom of the pages its behaving normally.

the code is as follows
app.vue

<script setup lang="ts">
    import CanvasComponent from "@/components/CanvasComponent.vue";

    const width = 3000;
    const height = 3000;

    window.addEventListener('wheel', (e) => {
        e.preventDefault();
    })
</script>

<template>
    <div :style="`width:${(width+80)}px; height:${(height+80)}px`" class="overflow-auto p-10">
        <svg viewBox="0 0 3000 3000" style="background-color:blue" :width="width  + 'px'" :height="height  + 'px'" xmlns="http://www.w3.org/2000/svg" version="1.1">
            <CanvasComponent :initial-x="300" :initial-y="400" initial-width="200px" initial-height="300px"></CanvasComponent>
        </svg>
    </div>
</template>

CanvasComponent.Vue

<script setup lang='ts'>
    import {nextTick, ref} from "vue";

    const {initialX, initialY, initialWidth, initialHeight} = defineProps<{
        initialX: number,
        initialY: number,
        initialWidth: string,
        initialHeight: string
    }>();

    const x = ref(initialX)
    const y = ref(initialY);
    const width = ref(initialWidth)
    const height = ref(initialHeight)

    const isDragging = ref(false);
    const offsetX = ref(0);
    const offsetY = ref(0);


    const dragStart = (e: MouseEvent) => {
        e.stopPropagation();
        e.preventDefault()

        isDragging.value = true;

        offsetX.value = e.clientX - x.value;
        offsetY.value = e.clientY - y.value;

        document.body.style.overflow = 'hidden'; // Prevent scrolling

        nextTick(() => {
            document.addEventListener('mousemove', drag);
            document.addEventListener('mouseup', dragEnd);
        });
    }

    const drag = (e: MouseEvent) => {
        e.stopPropagation();
        e.preventDefault();
        if(!isDragging.value) return;
        x.value = e.clientX - offsetX.value;
        y.value = e.clientY - offsetY.value;
    }

    const dragEnd = (e: MouseEvent) => {
        e.preventDefault();
        isDragging.value = false;

        document.removeEventListener('mousemove', drag);
        document.removeEventListener('mouseup', dragEnd);
    }

</script>

<template>
    <foreignObject class="drag-handle-class"
        :x="x"
        :y="y"
        :width="width"
        :height="height"
        @mousedown="dragStart"
    >
        <div class="w-full h-full bg-red-500 overflow-scroll drag-handle-class"></div>
    </foreignObject>
</template>

I tried preventing the scolling itself but that didnt work. as you can see in the video it works perfectly in firefox its just the chromium browsers that are being weird.

Connection from DB to HTML

<body>
    <div class="main-body">
       
        <div class="hotel-block">
            <img src="https://i2.photo.2gis.com/images/branch/0/30258560076741797_1cd9.jpg" alt="" class="hotel-1">
            <h2></h2>
            <p class="chertochka"></p>
            <h2></h2>
            <a class="click-btn btn-style2" href="./contact.html">List</a>
        </div>
        <div class="hotel-block">
            <img src="https://avatars.dzeninfra.ru/get-zen_doc/2404797/pub_5ec05dabc419064bb24dcdcb_5ec07408d54088764522e780/scale_1200" alt="" class="hotel-1">
            <h2></h2>
            <p class="chertochka"></p>
            <h2></h2>
            <a class="click-btn btn-style2" href="./contact.html">List</a>
        </div>
        <div class="hotel-block">
            <img src="https://www.worldrainbowhotels.com/wp-content/uploads/2019/05/Crown-Metropol-Perth.jpg" alt="" class="hotel-1">
            <h2></h2>
            <p class="chertochka"></p>
            <h2></h2>
            <a class="click-btn btn-style2" href="./contact.html">List</a>
        </div>
        <div class="hotel-block">
            <img src="https://alanya-invest.ru/upload/iblock/6e4/6e43b827a3ff50d381f95697957f30b5.jpg" alt="" class="hotel-1">
            <h2></h2>
            <p class="chertochka"></p>
            <h2></h2>
            <a class="click-btn btn-style2" href="./contact.html">List</a>
        </div>
        <div class="hotel-block">
            <img src="https://static.tildacdn.com/tild3537-6330-4633-a535-363963343564/IMG_5600_24-10-2018_.jpg" alt="" class="hotel-1">
            <h2></h2>
            <p class="chertochka"></p>
            <h2></h2>
            <a class="click-btn btn-style2" href="./contact.html">List</a>
        </div>
        <div class="hotel-block">
            <img src="https://s01.cdn-pegast.net/get/ff/7a/6a/14fc6c3317967b5913591d23b20ead97a39bc3027cc726ed1f4188c23a/5f3534cc2c556.jpg" alt="" class="hotel-1">
            <h2></h2>
            <p class="chertochka"></p>
            <h2></h2>
            <a class="click-btn btn-style2" href="./contact.html">List</a>
        </div>
    </div>
</body>
<footer>
    <div class="icons-list">
        <li class="icons">Phone number - 8 926 745 64 43</li>
        <li class="icons">Social Network - @grammyf</li>
    </div>
</footer>
<script src="bd.js">
const mysql = require('mysql');

const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'root',
  database: 'hotelsDB'
});

connection.connect((err) => {
  if (err) {
    console.error('Ошибка подключения к базе данных: ', err);
    return;
  }
  console.log('Подключение к базе данных успешно');

  connection.query('SELECT * FROM hotels', (err, rows) => {
    if (err) {
      console.error('Ошибка выполнения запроса: ', err);
      return;
    }

    const hotels = rows.map(row => {
      return {
        hotel_name: row.hotel_name,
        price: row.price,
        description: row.description
      };
    });

    'Массив отелей:', JSON.stringify(hotels)
    hotelsArray = hotels.splice(0, 6)
    console.log(JSON.stringify(hotelsArray.splice(0, 6)))
    
    module.exports = hotels; 
  });

  connection.end((err) => {
    if (err) {
      console.error('Ошибка закрытия соединения с базой данных: ', err);
      return;
    }
    console.log('Лан наебал оно опять открыто');
  });
});

const hotelBlocks = document.querySelectorAll('.hotel-block'); !!! 

hotelsArray.forEach(hotel => {
  const hotelElement = document.createElement('div');
  hotelElement.innerHTML = `
      <div class="hotel-block">
          <h2>${hotel.hotel_name}</h2>
          <p>Цена: $ ${hotel.price}</p>
          <p>${hotel.description}</p>
          <a class="click-btn btn-style2" href="./contact.html">List</a>
      </div>
  `;
  hotelsContainer.appendChild(hotelElement);
})
</script>

There is a data array in the variable hotelsArray that is formed as a result of the script. How can I transfer data from the JSON array to the HTML page? I tried selecting the .hotel-block tag and creating a loop for each element in the array to create div elements, but when I run the script in a separate file, it only outputs the array data. When I embed the script on the HTML page, the code doesn’t work. What can I do about this? I need to create divs with specific data on the page. How can I do this without using PHP, only JS and NodeJS

Prisma client error: cannot read properties of undefined

I have a web application built with an express.js backend, PostgreSQL db and use Prisma client. I have 2 separate POST routes in the app, /api/chat and /api/sendRecReview (code below). This web app is hosted on Render.

app.post("/api/chat", async (req, res) => {
  try {
    const clientIp = req.ip;
    const timestamp = new Date();
    const messageHistory =
      req.body.messageHistory.map((messageObj) => messageObj.User) || [];

    const answers = req.body.answers;

    console.log(messageHistory);
    const responseObj = await querydb(messageHistory, answers);
    const updatedMessageHistory = req.body.messageHistory.concat({
      AI: responseObj.text,
    });

    // Arrange club recs data to save in database
    const clubData = updatedMessageHistory[1].AI;
    const clubString = clubData.replace("```jsonn", "").replace("n```", "");
    const clubRecsToSave = JSON.parse(clubString);

    // Save IP address, timestamp, and recommendations to the database
    const session = await prisma.session.create({
      data: {
        clientIp: clientIp,
        timestamp: timestamp,
        answers: JSON.stringify(answers),
        recommendations: JSON.stringify(clubRecsToSave),
      },
    });

    res
      .status(200)
      .json({ messageHistory: updatedMessageHistory, clientIp: clientIp });
  } catch (error) {
    console.error(error);
    res
      .status(500)
      .json({ error: "An error occurred while processing the request" });
  }
});
app.post("/api/sendRecReview", async (req, res) => {

  try {
    const clientIp = req.ip; 
    const timestamp = new Date();
    const answers = req.body.answers;
    const recommendations = req.body.clubs;
    const rating = req.body.rating;

    const review = await prisma.review.create({
      data: {
        clientIp: clientIp, 
        timestamp: timestamp,
        answers: JSON.stringify(answers),
        recommendations: JSON.stringify(recommendations),
        rating,
      },
    });

    res.status(200).json({ response: "Rating Successful" });
  } catch (error) {
    console.error(error);
    res
      .status(500)
      .json({ error: "An error occurred while processing the request" });
  }
});
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?
// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model Session {
  id              String   @id @default(uuid())
  clientIp        String
  timestamp       DateTime @default(now())
  answers         String
  recommendations String
}

model Review {
  id              String   @id @default(uuid())
  clientIp        String
  timestamp       DateTime @default(now())
  answers         String
  recommendations String
  rating          String
}

When I hit both routes in localhost, the data correctly saves to both the Session table and the Review table in the database. When I run these on the Render hosted site, the data is correctly saved to the Session table but not the Review table. I get the below error telling me review is undefined when I run .create on it.

TypeError: Cannot read properties of undefined (reading 'create')
at file:///opt/render/project/src/index.js:258:25
at Layer.handle [as handle_request] (/opt/render/project/src/node_modules/express/lib/router/layer.js:95:5)
at next (/opt/render/project/src/node_modules/express/lib/router/route.js:144:13)
at Route.dispatch (/opt/render/project/src/node_modules/express/lib/router/route.js:114:3)
at Layer.handle [as handle_request] (/opt/render/project/src/node_modules/express/lib/router/layer.js:95:5)
at /opt/render/project/src/node_modules/express/lib/router/index.js:284:15
at Function.process_params (/opt/render/project/src/node_modules/express/lib/router/index.js:346:12)
at next (/opt/render/project/src/node_modules/express/lib/router/index.js:280:10)
at /opt/render/project/src/node_modules/body-parser/lib/read.js:137:5
at AsyncResource.runInAsyncScope (node:async_hooks:206:9)
==> Detected service running on port 10000
==> Docs on specifying a port: https://render.com/docs/web-services#port-binding

Migrations have been run and all code has been pushed to Github and deployed to Render. The only slight variation is the Review table was created separately as part of the second migration as where Session was part of the first migration. Can anyone think of why the Review table is not being recognized at runtime on Render but is working fine in localhost?

Difference between func.apply(this, args) and func(…args) in closures

I came across the following thing while trying to understand some concepts of working with closures.
When I was reading about memoization/throttling, people were using func.apply(this, args) in closures.

Here are some examples from 2 different sources:

function memoize(func) {
  const cache = {}
  return function(...args) {
    const key = JSON.stringify(args)
    if (cache[key]) {
      return cache[key]
    } else {
      const result = func.apply(this, args) // (*)
      cache[key] = result
      return result
    }
  }
}

and

function throttle(func, interval) {
  let isRunning = false;

  return function (...args) {
    if (!isRunning) {
      isRunning = true;
      func.apply(this, args); // (*)

      setTimeout(() => {
        isRunning = false;
      }, interval);
    }
  };
}

So my question is: can we use func(...args) instead? And what is the actual difference if we would call func with spread-operator instead of apply?

How to access Payload after accessing the Request url

Through Selenium in the Python language, I am working on testing the website, and I was able to access the link for the Request, and I want to access the Payload. Attached is an image that shows
enter image description here

driver = webdriver.Chrome(options=option)

driver.get("https://www.example.com")

network_entries = driver.execute_script(
    "return window.performance.getEntriesByType('resource');")

       
for entry in network_entries:
    target_url = entry['name']
    if("http://fonts.googleapis.com/css?family=Open" in target_url):
        

        print("URL:", target_url)
        # need print payload !!
        #print("PAYLOAD:", payload)

I keep getting net::ERR_BLOCKED_BY_CLIENT on the console and (status) blocked on the network tab

i have this code that makes a request to fetch an array from a laravel backend, on my local server, it runs smoothly but after i hosted it, i keep getting POST error “http://127.0.0.1:8000/retrieve net::ERR_BLOCKED_BY_CLIENT”

$.post("https://vgn.srgasaswsa.com", {
                // Retrieve CSRF token from the meta tag
                _token: document.querySelector(
                    '#registrationForm [name="_token"]'
                ).value,

                // Send the value of the selected item as a parameter
                data: item.value,
            })
                .done((res) => {
                    // Loop it as options in the corresponding Local government <select>
                    $.map(res, (item) => {
                        $(local).append(
                            ` <li class="hover:bg-red-800 hover:text-white hover:font-semibold">
                            <label for="${item}" class="w-full h-fit relative" x-on:click="isFocus = false, message = '${item}'">
                                <input type="radio"
                                            name="${local.substring(1)}"
                                            id="${item}"
                                            value="${item}"
                                            class="absolute top-0 left-0 w-full h-fit opacity-0 cursor-pointer"
                                >
                                <p class="w-full h-fit py-2 text-[50px] lg:text-[1em] lg:text-base font-normal">${item}</p>
                            </label>
                        </li>`
                        );
                    });
                })
                .fail((xhr, status, error) => {
                    console.error(error);
                });```

I changed the POST url affter hosting to the hosting url, but it still showing the same error, 

this is my laravel cors
'paths' => ['api/*', 'sanctum/csrf-cookie'],

'allowed_methods' => ['*'],

'allowed_origins' => ['https://vgn.srgasaswsa.com'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => [],

'max_age' => 0,

'supports_credentials' => true,

Embed cloudflare insights including sending data with javascript

I have the following html code to embed the Cloudflare Insights javascript into my website.

<script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "001e2db377654356d03acf35f1e5a"}'></script>

Because of the cookie law in the EU, I only want to load the script when someone accepts cookies. Therefore I’ve a javascript function where I load those third-party scripts only when someone accepts cookies.

How can I embed the Cloudflare Insights script including sending the data-cf-beacon data with my javascript function? My function now loads the cloudflare script, but doesn’t send the data-cf-beacon.

function BlockCookie() {
        var imported = document.createElement('script');
        imported.src = 'https://static.cloudflareinsights.com/beacon.min.js';
        document.head.appendChild(imported);  
    } ```