Boost and nprogress don’t seem to work when going back one page

I wanted to add nprogress to a demo application and show the progress bar only on boosted requests. My first idea was to do it like this:

window.addEventListener('htmx:beforeRequest', (event) => {
    if(event.detail.boosted) {
        console.log(event);
        NProgress.start();
    }
});
window.addEventListener('htmx:afterRequest', (event) => {
    if(event.detail.boosted) {
        console.log("Done")
        console.log(event)
        NProgress.done();
    }
});

However, when going back in history the NProgressBar gets shown again (see video) even though I wouldn’t expect it to show. I also created a demo Laravel application here.
Thank you in advance.

serverSideDataSource triggering twice in ag-grid

serverSideDataSource triggering twice in ag-grid, When the filter set on session and reloading the window. The below method triggering twice

 serverSideDataSource(count: number) {
        return {
          getRows: (params) => {
            //add sortModel for dynamically created columns
            params.request.sortModel.forEach((sortItem) => {
              if (sortItem.colId.split('&').length > 1) {
                const sortModelObj = {};
                sortItem.colId.split('&').forEach((subCol) => (sortModelObj[subCol] = { ...sortItem, colId: subCol }));
                params.request.sortModel = Object.values(sortModelObj);
              }
            });
            const sortModel = Object.keys(params.request.sortModel);
            let where = this.whereBy;
            if (this.filterStateWhere.length !== 0) {
              where = [...this.whereBy, ...this.filterStateWhere];
              const mainFilterModel = this.gridApi.getFilterModel();
              const filterStateModel = JSON.parse(this.cacheSvc.getState('session', `${this.viewType}/${'FilterState'}`));
              params.request.filterModel = { ...mainFilterModel, ...filterStateModel };
            }
            const filterModel = Object.keys(params.request.filterModel) as string[];
            this.payload = getDefaultPayload({
              params,
              gridOptions: this.gridOptions,
              order: this.orderBy,
              where,
              select: this.selectBy
            });
            this.payload.limit = this.gridOptions.paginationPageSize;
            // main server request
            if (filterModel.length !== 0) {
              this.filterChecks(params, filterModel, sortModel);
            } else {
              if (sortModel.length !== 0) {
                this.payload.offset = this.gridApi.paginationGetCurrentPage() > 0 ? params.request.startRow : 0;
                this.payload = this.applySortPayload(params.request.sortModel);
              }
              this.togglePagination(count);
              this.fetchItemsRequest(params, count);
            }
          }
        };
      }

Detecting if browser extension is running as popup or side panel

I’m building a browser extension that can be opened as both a popup and a side panel (chrome-based browsers) / sidebar (firefox). Is there a way in JavaScript to detect which option the user is currently using (where the application is loaded)?

This is a part of my manifest.json file:

{
  "manifest_version": 3,
  "permissions": [
    "storage",
    "unlimitedStorage",
    "activeTab",
    "tabs",
    "sidePanel",
    "declarativeNetRequestWithHostAccess"
  ],
  "action": {
    "default_popup": "index.html"
  },
  "background": {
    "service_worker": "js/background.js"
  },
  "side_panel": {
    "default_path": "index.html"
  },
  "sidebar_action": {
    "default_panel": "index.html",
    "default_icon": "icons/icon_128.png"
  }
}

For both extension and side panel the sidePanel is present in the browser object and I didn’t notice any differences there.

Failed to construct ‘ResizeObserver’: parameter 1 is not of type ‘Function’

I am trying to render HTML inside textarea and I have an ajax call from the controller to read the value and parse it as var to the render() function.

I followed the question here

However, the render() function failed when I tried to use ResizeObserver within the ajax call. If I specifically define var explain = "<b style ="color:blue;">Risky</b>";, the content can be rendered in onload but not within the ajax call.

May I know what am I missing here?

These are my codes:

@Html.TextArea("", new { @id = "box", @oninput = "render()"})

<script type="text/javascript">
    $(document).ready(function () {

      var job_ID = "1";
      var explain = "";

        onload = function () {
                LoadJobResult(job_ID);         
        }

function render() {

            var inp = document.getElementById("box");
            
            var data =
                `<svg xmlns="http://www.w3.org/2000/svg" width="${inp.offsetWidth}" height="${inp.offsetHeight}">
                <foreignObject width="100%" height="100%">
                <div xmlns="http://www.w3.org/1999/xhtml" style="font-style: normal; font-variant: normal; font-size:13.3px;padding:2px;">
                ${inp.value} <i style="color:red">Model Explanation</i>
                </div>
                </foreignObject>
                </svg>`;

            var blob = new Blob([data], { type: 'image/svg+xml' });
            var url = URL.createObjectURL(blob);
            inp.style.backgroundImage = "url(" + URL.createObjectURL(blob) + ")";
        }


function LoadJobResult(ID) {
            $.ajax({
                url: '/controller/Get_JobResult',
                type: 'Get',
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                data: { 'job_ID': ID },
                success: function (result) {
                    var res = JSON.parse(result);

                    $("#box").val(res[0]['DRP_Explanation_Txt']);
                    explain = res[0]['DRP_Explanation_Txt']; 
                    
                    render();
                    ro = new ResizeObserver(render());
                    ro.observe(document.getElementById("box"));
                },
                error: function (emp, err) {
                    console.log('my message' + err);
                }
            });         
        }
  });


</script>

How to fetch text format response from API in frontend

I am getting a response “executed successfully” in text/html format from API with status code 200.

I want to show response to user through notification.

I tried to store that response in response but It’s not working, I’m getting blank response.

Export const abctrigger = (payload, signal) => {
  Return fetch(API_URL, {
    method: post,
    Signal: signal
    Body: JSON.stringify(payload),
    headers: {
      Content-Type : 'application/json'
    }
  })
    .then((response) => response.text())
    .then((response) => {
      Return response;
    })
}

I tried by changing and removing headers and also used .text() method but still getting problem.

Everything is working fine in backend.

I want to store text/html format response from API in response and show that to user through notification.

Can i write a program in JavaScript to count the number of vowels using string.includes() and for of loop? [closed]

I have tried passing strings to the getCount function that contain ‘aeiou’ and not but the value vowelsCount is always 0.

I tried using string includes() function using the documentation provided by the very kind and helpful mdnwebdocs, but it always returns count as 0, I have the code with which we can get the exact number of vowels in a string, but I prefer to use the approach taught by mdnwebdocs.

Supplying a reason for AbortController?

This code aborts the request after 10 ms:

const controller = new AbortController();
const signal = controller.signal;


fetch('https://jsonplaceholder.typicode.com/todos/1', {
        signal
    })
    .then(response => response.json())
    .then(data => {
        console.log('Data:', data);
    })
    .catch(err => {
        console.log(err)
        if (err.name === 'AbortError')....

    });

 
setTimeout(() => {
    controller.abort();
 
}, 10);

Output :

DOMException: signal is aborted without reason

Question:
If it says “without a reason,” is it possible to supply a reason?
Because otherwise, the message is a bit strange, as if I could supply a reason but didn’t.

Swiper slider not loading initially when Slides per view is more than 1

I’m using the swiper slider in the my website.

When I have slides per view more then 1 for example, 4 then when I load page 1 slide showing then after sometime it adjust to 5 slides in swiper slider.

https://swiperjs.com/swiper-api

<!-- Slider main container -->
<div class="swiper">
  <!-- Additional required wrapper -->
  <div class="swiper-wrapper">
    <!-- Slides -->
    <div class="swiper-slide">Slide 1</div>
    <div class="swiper-slide">Slide 2</div>
    <div class="swiper-slide">Slide 3</div>
    ...
  </div>
  <!-- If we need pagination -->
  <div class="swiper-pagination"></div>

  <!-- If we need navigation buttons -->
  <div class="swiper-button-prev"></div>
  <div class="swiper-button-next"></div>

  <!-- If we need scrollbar -->
  <div class="swiper-scrollbar"></div>
</div>

var slider = new Swiper(".swiper-container", {
                "slidesPerView":"4",
                "slidesToScroll":1,
                "spaceBetween":15,
                "freeMode":false,
                "loop":true,
                "lazy":true,
                "preloadImages":false,
                "swiperElementNodeName": 'swiper-container',
                "autoplay": {
                    "delay": 2500
                },
                "navigation":{
                    "nextEl":".swiper-button-prev",
                    "prevEl":".swiper-button-next"
                },
                "breakpoints":{
                    "1200":{
                        "slidesPerView": 4
                    },
                    "767":{
                        "slidesPerView":2.5,
                        "freeMode":true,
                        "loop":true
                    },
                    "480":{
                        "slidesPerView":1.5
                    }
                }
            });

When page render slides width should calculate and 4 slides should display from initial page load.

Firebase Authentication and Storage: Error Accessing user.user.uid [duplicate]

I’m trying to create a user account and upload an image to Firebase Storage using Firebase Authentication and Firestore. However, I’m encountering an error when trying to access user.user.uid ,Here’s my code:

import {
  auth,
  createUserWithEmailAndPassword,
  doc,
  setDoc,
  storage,
  ref,
  uploadBytes,
  getDownloadURL,
} from "../utilis/utilis.js";

const sumbitForm = document.getElementById("sumbitForm");

sumbitForm.addEventListener("submit", function (e) {
  e.preventDefault();
  console.log(e);
  const img = e.target[0].files[0];
  const email = e.target[1].value;
  const password = e.target[2].value;
  const firstName = e.target[4].value;
  const lastName = e.target[5].value;
  const phone = e.target[6].value;
  const company = e.target[7].value;
  // console.log(img);

  const userInfo = {
    img,
    email,
    password,
    firstName,
    lastName,
    phone,
    company,
  };

  console.log(userInfo);

  //Creating Account
  createUserWithEmailAndPassword(auth, email, password)
    .then((user) => {
      console.log("user=>", user.user.uid);
    })
    .catch((err) => {
      alert(err);
    });

  //Uploading Image
  const userRef = ref(storage, `user/${user.user.uid}`); //error
  uploadBytes(userRef, img)
    .then(() => {
      console.log("user image uploaded");
//getting url of img that we uploaded
      getDownloadURL(userRef)
        .then((url) => {
          console.log("We got a URL", url);
        })
        .catch((err) => {
          console.log("We cant get the URL from FireBase");
        });
    })
    .catch(() => {
      console.log("Error in uploading image");
    });
});

I’m getting an error on the line where I try to create a reference to the user’s storage location using user.user.uid:

I tried moving the line const userRef = ref(storage, ‘user/${user.uid}’); inside the .then block where the user object is created, but I’m still encountering issues.

How can I correctly create the user account and upload the user’s image to Firebase Storage, ensuring that I can access the user.uid after the user object is created?

Any help or guidance on this issue would be greatly appreciated!

How to trigger bootstrap toast ? other then button type=”button”, or fetch()

Is there a simple, other solution to trigger my boostrap toast ?
Maybe like :
button onclick ="trigger my bootstrap toast the easy way"
Without the need of fetch or a button type=”button”.
I think i have overseen a simple way to implenet it.

My sitecode looks like :

<form> <button=type"submit" name="need the name for my json key" value="need you also for my json"
To my PHP background app, to save my value to json strings in a file.
Is there any simpler way to implement the call to trigger bootstrap toast?
The PHP background side is not the problem, I just want to POST my values to my PHP.

How Do i run an FTP script through Cypress?

I have an FTP script that needs to be run in the CMD for me to be able to add a file in the website, now my main work is to automate testcases using cypress and a testcase requires me to get a new file so i have to manually run my ftp script in CMD again and again SO i was wondering if there is a way to automate that as well.

I tried using some node modules like basic-ftp and ssh2-sftp-client but was not able to get it

How can I set background color to transparent with Phaser 3?

Trouble

I added two Text objects to a scene.
But for the latter one, I couldn’t set background color to transparent.

Can anyone help me?

Here is the screenshot.

Screenshot


What I tried

I want the Text objects to have transparent background.

I have tried to set backgroundColor like:

this.scene.add.text(0, 0, "hoge", {
  backgroundColor: "rgb(255 255 255 / 0.5)",
});

but it doesn’t work.

Screenshot


Source Code

This Text object looks good. It has transparent background.

    this.text = (() => {
      const text = this.scene.add.text(0, 0, "x: -, y: -", {
        padding: {
          y: 50 / this.scene.cameras.main.zoom,
        },
        align: "center",
        fixedWidth: containerWidth,
        fixedHeight: containerHeight,
        fontSize: `${100 / this.scene.cameras.main.zoom}px`,
        lineSpacing: 0,
      });

      return text;
    })();

This Text looks bad. It has black background.

    this.text = (() => {
      const text = this.scene.add.text(0, 0, [
        "a10a",
        "VIT: 0",
      ], {
        fixedWidth: containerWidth,
        fixedHeight: containerHeight,
        fontSize: `${100 / this.scene.cameras.main.zoom}px`,
      });

      return text;
    })();

Javascript promises: Why does return in nested then chain change result order?

I’m new to JS Promises and am trying to understand why I get different results depending on if I have a return or not on this line: return foo(2).then(() => {

function foo(num) {
  console.log(num)
  return new Promise(resolve => setTimeout(resolve, num * 1000));
}

foo(1).then(() => {
  return foo(2).then(() => {
    console.log(4)
  });
}).then(() => {
  foo(3)
})

vs

function foo(num) {
  console.log(num)
  return new Promise(resolve => setTimeout(resolve, num * 1000));
}

foo(1).then(() => {
  foo(2).then(() => {
    console.log(4)
  });
}).then(() => {
  foo(3)
})

Why does the order of 4/3 change?

Handle Http 302 response on Django view and Javascript async function

For strict security, how can I implement redirect on Django view in response to a JS async call that only updates a div InnerHTML? That is the first preference.

I tried JS client-side redirect in multiple ways. I didnt work either.

When user’s session is ended, server returns 302 Location: /. To take the user to the home page.

View

@csrf_protect
def edit_form(request):

    if not request.user.is_authenticated:
         return redirect('/')

    form = userForm()
    return render(request, 'edit_form.html', {'form': form})

JS

async function fetch_form() {
try {
    const response = await fetch('http://192.168.1.10:8000/edit_form',{
        method: 'GET',
    });
    if (!response.ok) { //redirect didn't work
        const redirectUrl = response.headers.get('Location');
        console.log(redirectUrl);
        window.location.href = redirectUrl;
        //throw new Error('Network response was not ok ' + response.statusText);
    } else if (response.status === 302) { //redirect didn't work
        const redirectUrl = response.headers.get('Location');
        console.log(redirectUrl);
        window.location.href = redirectUrl;
    }
    document.getElementById('firstModal').innerHTML = data;
} catch (error) {
    console. Error('There has been a problem with your fetch operation:', error);
}
};


async function fetch_form() {
try {
    const response = await fetch('http://192.168.1.10:8000/edit_form',{
        method: 'GET',
    });
    if (!response.ok){
        throw new Error('Network response was not ok ' + response.statusText);
    }
    document.getElementById('firstModal').innerHTML = data;
} catch (error) {
    if (error.response.status === 302) { //redirect didn't work
        const redirectUrl = response.headers.get('Location');
        console.log(redirectUrl);
        window.location.href = redirectUrl;
    console.error('There has been a problem with your fetch operation:', error);
    }
}
};