How to include credentials when sending a request with React Server Components?

As the title says I am trying to check if my user is logged on, and if they are an admin.
This is the code:

import LoginFormComponent from "@/components/admin/login-form-component/login-form-component";
import LogoComponent from "@/components/logo-component/logo-component";
import IsAdminFunction from "@/scripts/requests/user/is-admin-function";
import { cookies, headers } from "next/headers";
import dynamic from "next/dynamic";

export default async function AdminLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const staticData = await fetch(`http://localhost:8878/api/user/isadmin`, {
    method: "GET",
    credentials: "include", // Include cookies with the request
  })
    .then((response) => response.json()) // Parse the response as JSON
    .then((data) => {
      console.log(data); // Print the response data
      return data; // Return the response data for further processing
    })
    .catch((error) => {
      console.error("Error:", error); // Log any errors
      throw error; // Re-throw the error for further handling
    });

  console.log(staticData);
  return (
    <>
       // this is the same as the fetch above, but this one is axios, 
       both are behaving identically
      {(await IsAdminFunction()).success == true ? (
        children
      ) : (
        <div className="center-div">
          <LogoComponent size={50} />
          <LoginFormComponent />
        </div>
      )}
    </>
  );
}

For some reason it always tells me that my user is not an admin, even though I’ve logged on already. I found out on my backend that the cookies are null, and I’ve tried adding it manually, but when I use cookies or headers from next/headers it just gives me this error.

Error: Page with `dynamic = "error"` couldn't be rendered statically because it used `cookies`. 

I know I am doing something wrong here, how should I approach this? I am also using "next": "14.0.4",.

Is there a way in which I can search for a shop using a keyword input and address input in Nodejs and React

I have a shop schema that has shopname and adress among others. The getShops controller function has APIFeatures as a search utility. However, the search only uses a keyword, that navigates to the search/keyword on submitting. However, I want to get a shop using keyword input and address input. How do I go about it?

This is the get shops controller function

exports.getShops = catchAsyncErrors(async (req, res, next) => {

 const resPerPage = 50;
 const shopsCount = await Shop.countDocuments();

 const apiFeatures = new APIFeatures(Shop.find(), req.query)
 .search()
 .filter()
 .pagination(resPerPage)
 const shops = await apiFeatures.query;
 setTimeout(() => {
   res.status(200).json({
     success: true,
     shopsCount,
     resPerPage,
     shops,
   })
 }, 2000);


});

The APIFeatures file is this

   constructor(query, queryStr) {
       this.query = query;
       this.queryStr = queryStr;
   }

   search() {
       const keyword = this.queryStr.keyword
       ? {
           $or: [
             { words: { $regex: this.queryStr.keyword, $options: "i" } },
             { address: { $regex: this.queryStr.keyword, $options: "i" } }
           ]
         }
       : {};

       this.query = this.query.find({ ...keyword });
       return this;
   }



   filter() {
       const queryCopy = { ...this.queryStr };
       // Removing fields from the query
       const removeFields = [ 'keyword', 'adress', 'limit', 'page' ]
       removeFields.forEach(el => delete queryCopy[el]);

       this.query = this.query.find(queryCopy);
       return this;
   }


}

module.exports = APIFeatures;

This is the shopActions for getshops

   try {
       dispatch({ type: ALL_SHOPS_REQUEST})
       const { data } = await axios.get(`/api/v1/shops?keyword=${keyword}&page=${currentPage}`)

       dispatch({
           type: ALL_SHOPS_SUCCESS,
           payload: data
       })
   } catch (error) {
       dispatch({
           type: ALL_SHOPS_FAIL,
           payload: error.response.data.message
       })
   }
   
 }

Here is the srach componenet in layout folder

import { useNavigate } from 'react-router-dom'


const Search = () => {


   const [keyword, setKeyword] = useState('');

   const navigate = useNavigate();

   const searchHandler = (e) => {
       e.preventDefault()

       if(keyword.trim()) {
           navigate(`/search/${keyword}`)
       } else{
           navigate('/')
       }
   } 
   return (
       <form onSubmit={searchHandler}>
         <div className="input-group">
           <input
             type="text"
             id="search_field"
             className="form-control"
             placeholder="I am looking for..."
             onChange={(e) => setKeyword(e.target.value)}
           ></input>

           <div className="input-group-append">
             <button id="search_btn" className="btn">
               <i className="fa fa-search" aria-hidden="true"></i>
             </button>
           </div>
         </div>
       </form>
     )
}

export default Search

Finally, here is the APP.js routes

import Header from "./components/layout/Header";
import Footer from "./components/layout/Footer";
import Shop from "./components/Shop";
import ShopDetails from './components/shop/ShopDetails'
import "./App.css";

function App() {
 return (
   <Router>
     <div className="App">
       <Header />
       <div className="big-container">
       <Routes>
         <Route path="/" element={<Shop />} exact />
         <Route path="/search/:keyword" element={<Shop/>} exact />
         <Route path="/shop/:id" element={<ShopDetails />} exact />
       </Routes>

       </div>

       <Footer />
     </div>
   </Router>
 );
}

export default App;

Ith thise files, I am confined to only searching for the shop using keyword. However, I want to be able to input both keyword value and address value and get shops according to keyword and address.

Get input[type=”text”] to wrap

I have a datalist attached to a text input of type = “text”. Using JavaScript, I have enabled the user to select multiple options from the datalist. However, I need the input to wrap when the text starts to overflow. I CANNOT use a textarea element for this as it is not compatible with datalist.

To Set a System Variable Value With JavaScript API in AutoCAD

I’m trying to follow this guide (https://help.autodesk.com/view/OARX/2024/ENU/?guid=adsk_jsdev_set_a_system_variable_value_to) but it is not working when i try to do it on my AutoCAD. What am I doing wrong?

  • I already set the TRUSTEDDOMAINS
  • I already test the async function with a alert() and the code is going in the arg.set_value line, but does not trigger the function.

Acad.SystemVariableCollection.getSystemVariable(“COORDS”).then(function(arg){arg.set_value(1);alert(“response ok”)},function(){alert(“set failed!”)});

I tried to set the System Variable “COORDS” from 0 to 1, but it didnt change.

Problem importing a .glb file using import.meta.url in Three.js using parcel bundler

Hi I startet to make a little Game for me and my Friends with Three.js. I watched many tutorials on how to import .gltf and .glb files. Im using the parcel bundler and the command: npx parcel ./src/index.html
to start my project. I am searching for an answer for about 2 months now and i cant find a working solution.
My Code is

import * as THREE from 'three';
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
new GLTFLoader().load( new URL( 'terrain.glb', import.meta.url ), gltf => { 
  let model = gltf.scene;
  model.position.y += 0.48;
  scene.add(model);
});

My Html is

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Car Game</title>
    <style>
        body {
            margin: 0
        }
    </style>
</head>
<body>
    <script src="./js/scripts.js" type="module"></script>
</body>
</html>

and this is my file structure if it helps
My Structure

to install three I used: npm install three
and to install parcel i used: npm install parcel-bundler –save-dev

when i run it the screen shows nothing and an error shows up:
scripts.cd665a19.js:42930 Uncaught SyntaxError: Cannot use ‘import.meta’ outside a module (at scripts.cd665a19.js:42930:65)

I also tried it like this

const loader = new GLTFLoader();
loader.load('terrain.glb', (gltf) => {
    let model = gltf.scene;
    model.position.y += 0.48;
    scene.add(model);
});

but when i run this it doesent show the 3d object. The error says that a script tag: “<” is missing
as far as i know that means that the object is seen as an Html file.

I also tried to remove the type=”module” tag from my index.html file because parcel showed an error about the module type but nothing changed.

I really dont know any further and I only have half a year experience with three.js and about a year of experience with js in webdeveloping. Please excuse me if i forgot something this is my first questing on stackoverflow and my english is probably not the best because im from Germany and still only 14yo.
Thanks for helping in advance 🙂

FLexbox Dropdown Menu is making Sub categories Stand in a Line Instead of Being Stacked

i got a problem with this website i been working on

i want the navigation dropdown to look organized with the subcategories that are under the main categories, stacked on top of each other, without it affecting the navigation bar, but right now the sub categories are in a line/horizontal mode and they go off screen in the dropdown menu.

Bad dropdown
good dropdown

i was tryna figure out the issue and i found out that when i comment out the “display flex” under “.navbar .main-menu ul” and padding under “.navbar ul li a” in css, the dropdown menu gets fixed, but the navigation bar gets messed up. How do i fix this?

the issue is here

css

.navbar .main-menu ul {
    display: flex;
    
    
}

.navbar ul li a {
    padding: 32px 20px;
    display: block;
    font-weight: 600;
    transition: 0.2s;
    
}

Tab has large memory

I’ll start with the fact that I use ajax to load elements and noticed that without manually reloading the page, the memory in the tab began to grow. Looking at the console, I was convinced that the problem was in the images.

And so I load the data using ajax, then the clicks on the element and the image is drawn in the new element something like this

let image = new Image();
image.src = item.url;
image.onload = function() {
    previewContent.css('background-image', 'url(' + item.url + ')');
    image = null;
};

(loading method is not important)

to close I use использую previewContent.remove(), but this does not remove from Application - Frames - Image

I repeat loading data from ajax, open the image and see that inside Application - Frames - Image the same image has been added again and the memory of the tab has increased.

enter image description here

What can you do about it? or refuse to load data from ajax?

Ativador Windows 10 Download Gratis (32 bit 64 bit) PT-BR 2024

O Ativador Windows 10 desbloqueia todo o potencial de seu Microsoft Windows 10. Esse Ativador foi projetado para desbloquear todas as versões, incluindo o Windows 10 Pro, Home e Enterprise, e essa ferramenta garante que seu sistema esteja totalmente funcional em poucos instantes. Nossos ativadores são 100% confiáveis. Os Ativadores do Windows 10 também são ferramentas universais capazes de reviver suas versões do Microsoft Office. Você pode obter a melhor experiência que o Windows 10 tem a oferecer e garantir uma operação tranquila com nossos ativadores recomendados.

Ativação do Windows 10 Pro
Você está procurando uma maneira de usar o Windows sem comprar nenhuma chave de licença? O baixar ativador windows 10 é sua resposta. É uma ferramenta que lhe dá uma licença permanente do Windows, para que você possa usá-lo para sempre sem pagar um centavo. Talvez você esteja se perguntando como essa ferramenta funciona ou como usá-la. Você está no lugar certo!

Este guia responde a essas perguntas e muito mais. Há um mundo de ferramentas on-line, como o licença do windows 10 Ativatod, que pode ativar o Windows para você. Elas usam códigos especiais para gerar uma chave que ativa seu Windows. Mas lembre-se, se você não gosta de usar um ativador, a melhor opção é comprar uma licença. Continue lendo para saber mais.

Ativar o Windows 10 com o KMSpico
Quando se trata de ativar o Windows 10, o KMSpico se destaca como uma ferramenta líder. Para aqueles que não estão familiarizados, o KMSpico é um ativador gratuito renomado que provou sua confiabilidade ao longo do tempo. Considerado o melhor entre os ativadores gratuitos para o Windows 10, sua popularidade tem se mantido forte.

Então, você instalou recentemente o Windows 10 e recebeu a mensagem “Vá para as configurações do PC para ativar o Windows”? Se sim, a solução é mais simples do que você imagina: Faça o download do ativador KMSpico. Em apenas 3 minutos, você terá seu Windows 10 totalmente ativado, e isso também de graça.

A Team Daz, um nome sinônimo de ativadores confiáveis, é o gênio por trás do ativador windows 10 kmspico. Sua lealdade resultou em um ativador que é estável e fácil de usar. Portanto, se você tem vasculhado a Internet em busca de um ativador confiável para o Windows, sua busca termina aqui. O KMSpico conquistou sua posição como o melhor ativador do Windows 10 que existe.

KMSPico Ativador Windows 10
Se for o Windows 10 Pro ou qualquer outra versão, o KMSpico ativa todas elas. Além disso, sua proeza não se limita ao Windows; ele também pode ativar o Microsoft Office.
O KMSpico não oferece apenas qualquer ativação; ele fornece uma licença digital genuína.
Ao contrário de muitos outros ativadores, o ativador windows 10 kmspico opera sem problemas off-line, trocando sua chave atual por uma nova sem problemas.
Principais recursos do KMSpico Windows 10 Activator
O KMSpico promete e fornece a ativação original do Microsoft Windows, um sistema mundialmente confiável.
Além do Windows, o KMSpico ativa o Microsoft Office, que é essencial para muitas profissões, especialmente no setor bancário.
Se você estiver executando um sistema de 32 ou 64 bits, o KMSpico tem tudo o que você precisa.
O KMSpico garante que seu Windows ou Office permaneça ativado por toda a vida.
Use o KMSpico em qualquer número de dispositivos, sem limitações.
Não há necessidade de se preocupar com malware ou vírus; o KMSpico é 100% seguro e tem o respaldo de verificações completas de vírus.
Com o KMSpico Portable, ative o Windows ou o Office sem nem mesmo instalar o ativador.
Como usar o KMSPico
Clique no link fornecido para obter o ativador do KMSPico para Windows 10.
Antes de continuar, verifique se o firewall do Windows está desativado.
Use o WinRAR para abrir o arquivo baixado.
Localize a pasta e instale o ativador do KMSPico.
Depois de instalado, você verá um ícone do ativador na área de trabalho.
Clique nesse ícone e selecione a opção “Ativar o Windows”.
Aguarde alguns minutos e seu Windows 10 estará totalmente ativado.
Microsoft Toolkit de Ativação do Windows 10
Quando se trata de Ativador Windows 10 com eficiência, o Microsoft Toolkit se destaca. Porque ele identifica de forma inteligente sua versão do Ativador Windows 10, bem como qualquer pacote do Microsoft Office instalado e, em seguida, se concentra no método de ativação ideal.

A pergunta que muitos usuários têm em mente O Microsoft Activator Toolkit para Windows 10 é confiável? Com certeza! Esse kit de ferramentas, também conhecido como Windows 10 Pro Activator, é conhecido por sua capacidade de ativar quase todos os sistemas Windows existentes. E se você estiver se perguntando sobre sua importância, lembre-se de que um Windows 10 não ativado não pode aproveitar todo o seu potencial. Há outros ativadores disponíveis, como o download do ativador do Windows 10, mas o Microsoft Toolkit garante uma ativação tranquila, mesmo em métodos como atualizações do sistema.

Recursos do Microsoft Toolkit Windows 10 Activator
Ele funciona mesmo sem a Internet; só precisa se conectar ao servidor KMS.
Se houver um problema com o servidor KMS, não se preocupe; você pode ativá-lo novamente com rapidez.
Um servidor KMS pode ajudar até 1.000 usuários, tornando as coisas simples e eficientes.
Muitos acreditam que essa é a melhor ferramenta para ativar o Windows 10.
Como usar o Microsoft Toolkit for Activator Windows 10
Use o link fornecido para baixar a configuração do Activator.
Antes de começar, certifique-se de desativar o firewall do Windows.
Abra o arquivo que você baixou com o WinRAR.
Localize a pasta e comece a instalar o ativador.
Após a instalação, você verá um novo atalho na área de trabalho.
Clique nele e selecione “Ativar o Windows”.
Aguarde um momento e pronto! Seu Windows 10 agora está totalmente ativado.
Ativador Windows 10 Loader
Você já se perguntou se o Ativador Windows 10 Loader é a melhor opção para Ativador Windows 10? A resposta está em um ativador universal chamado reloader. Essa ferramenta não é apenas popular, mas também altamente eficaz. Com ela, você pode colocar seu Ativador Windows 10 em funcionamento em apenas alguns minutos. Na verdade, se você acabou de instalar o Windows 10, recomendamos que experimente o reloader imediatamente.

Ao longo do tempo, o Windows desenvolveu várias versões. A cada lançamento, os ativadores evoluíram, tornando-se ainda mais fáceis de usar e confiáveis. O Windows 10 Ativatod de 2021 é a prova desse progresso. Hoje, ferramentas como o Windows Loader conquistaram um nicho para si mesmas, principalmente por causa de sua usabilidade direta e resultados garantidos.

Recursos do Windows 10 Loader
Este é um ativador sem intervenção. Ele trabalha para você.
Ele pode ativar instantaneamente qualquer versão do Windows ou do Office.
Depois de ativado, você pode remover o programa.
É simples, confiável e cumpre o que promete.
Chave de produto do Windows 10
Chaves do Windows 10 Home Edition

YTMG3-N6DKC-DKB77-7M9GH-8HVX7

BT79Q-G7N6G-PGBYW-4YWX6-6F4BT

chave de produto kmspico do Windows 10 Windows 10 Education

YNMGQ-8RYV3-4PGQ3-C8XTP-7CFBY

NW6C2-QMPVW-D7KKK-3GKT6-VCFB2

Windows 10 Enterprise

CKFK9-QNGF2-D34FM-99QX2-8XC4K

NPPR9-FWDCX-D2C8J-H872K-2YT43

PBHCJ-Q2NYD-2PX34-T2TD6-233PK

Chave de produto do Windows 10 Pro

VK7JG-NPHTM-C97JM-9MPGT-3V66T

6P99N-YF42M-TPGBG-9VMJP-YKHCF

8N67H-M3CY9-QT7C4-2TR7M-TOXIC

W269N-WFGWX-YVC9B-4J6C9-T83GX

Requisitos do sistema
Processador: 1 GHz ou mais rápido
RAM: 1 GB para 32 bits, 2 GB para 64 bits
Disco rígido: 16 GB para sistema operacional de 32 bits, 32 GB para sistema operacional de 64 bits
Gráficos: DirectX 9 com driver WDDM 1.0
Tela: resolução de 800×600
Internet: Necessária para atualizações e alguns recursos.
Como usar o Windows 10 Loader
Comece fazendo o download do Ativador Windows 10 Loader usando o link fornecido.
Extraia o arquivo baixado com o WinRAR.
Abra a pasta extraída e configure o ativador.
Você verá um novo atalho na área de trabalho assim que ele for concluído.
Clique nele e clique na opção “Ativar o Windows”.
Aguarde alguns instantes e pronto: o Windows está ativado

O Ativador Windows 10 desbloqueia todo o potencial de seu Microsoft Windows 10. Esse Ativador foi projetado para desbloquear todas as versões, incluindo o Windows 10 Pro, Home e Enterprise, e essa ferramenta garante que seu sistema esteja totalmente funcional em poucos instantes.

Form submit and on:click from the same button in SvelteKit

I’m trying to implement a “follower” functionality for an app. I have a table in my DB to track which Users are following which, and on each user’s page, I want there to be a button to follow that user. I have tied this button to a reactive variable so that the state of the button (saying “Follow User” if you are not following and “Unfollow User” if you are) will update automatically.

The following is how I’ve opted to do this, where isFollowing is the reactive variable.


          <!-- Only show "add follower" button if the page is not your own user page AND you are not already following -->
          {#if user.id != localUserId && !isFollowing}
            <TableBodyCell>
              <form method="POST" action="?/followUser" on:click={() => toggleIsFollowing()}>
                <Button type="submit"> 
                  <PlusSolid class="h-10 w-10 fill-current text-[#333333] hover:cursor-pointer" />
                </Button>
                <Heading customSize="mb-2 text-2xl font-extrabold" style="color:#333333"> Follow </Heading>
              </form>
            </TableBodyCell>
          {/if}

          <!-- Show unfollow button if you are following -->
          {#if isFollowing}
            <TableBodyCell>
              <Button type="submit"> 
                <MinusSolid class="h-10 w-10 fill-current text-[#333333] hover:cursor-pointer" on:click={() => toggleIsFollowing()}/>
              </Button>
              <Heading customSize="mb-2 text-2xl font-extrabold" style="color:#333333"> Unfollow </Heading>
            </TableBodyCell>
          {/if} 

However, when I set up the Button to both submit the form and toggle the reactive variable via on:click, the on:click is the only performed, and the form not submitted. Is there a better way to do this?

Running Google Form iframe in HTML file as a success message

My code adds data to a Sheet, then, as a successmessage, it opens a new tab in the browser with a Google Form in it. But I want it to open the Google Form in the same tab and not a new tab. This needs to happen in a mobile browser (Chrome mobile).

So I tried using the iframe code but I can only manage to append the iframe to my current HTML form once the code ran successfully. I can’t seem to replace the current form with the new Google Form.

Here’s the success message function with the normal window.open statement which opens a new tab every time:

function showSuccessMessageIn() {
      // Redirect to the desired URL
      window.open("https://docs.google.com/forms/d/e/***/viewform?usp=sf_link", "width=800,height=600"); 
    }

And here’s the Sign IN button from the original form (there are 4 more elements in the form though, and they all need to be replaced by the Google form when the success message runs):

<form>
    onclick="sample3(this.parentNode.parentNode); return false;">Sign IN</button> </p>
    <p> <button class="sign-out" size="20" type="submit" 

My service worker is not connecting to my content script in my Chrome extension. How do I fix this?

I have been working on porting this manifest v2 Chrome extension to manifest V3 and while I did port the extension through changing the structure in the manifest file and replacing the background.js with service-worker.js. The structure of the directory of the Chrome extension seems acceptable and should work in manifest v3, but I have a persistent problem that I cannot get around. I get an error message that states…

“Error: Could not establish connection. Receiving end does not exist.”

“Stack Trace”

“service-worker.js:14 (anonymous function)”

Here is my service-worker.js code to put it into context.

function sendAudioMessage(actionType, audioFile) {
  chrome.tabs.query({
      active: true,
      currentWindow: true
  }, function(tabs) {
      tabs.forEach(async (tab) => {
          console.log(tab);
          if (tab.url.startsWith("chrome")) return false;
          try {
              await chrome.tabs.sendMessage(tab.id, {
                  action: actionType
              });
          } catch (e) {
              console.error(e);
              console.trace();
          }
      });
  });
}

chrome.webNavigation.onCreatedNavigationTarget.addListener(onNav);
chrome.webNavigation.onBeforeNavigate.addListener(onNav);
chrome.webNavigation.onReferenceFragmentUpdated.addListener(onNav);
chrome.webNavigation.onHistoryStateUpdated.addListener(onNav);

function onNav(props) {
  const {
      frameId
  } = props;
  console.log(props);
  if (frameId > 0) return;
  sendAudioMessage('playNavigationSound');
}

chrome.downloads.onChanged.addListener(delta => {
  if (delta.state && delta.state.current === "complete") {
      sendAudioMessage('playDownloadCompleteSound');
  }
  if (delta.error && delta.error.current) {
      sendAudioMessage('playDownloadErrorSound');
  }
});

chrome.tabs.onUpdated.addListener((tabId, {
  mutedInfo
}) => {
  if (mutedInfo && mutedInfo.reason === "user") {
      sendAudioMessage('playMuteWarningSound');
  }
});

function changeVolume(volumeLevel) {
  chrome.tabs.query({
      active: true,
      currentWindow: true
  }, function(tabs) {
      tabs.forEach(async (tab) => {
          if (tab.url.startsWith("chrome")) return;
          try {
              await chrome.tabs.sendMessage(tab.id, {
                  action: 'changeVolume',
                  volume: volumeLevel
              });
          } catch (e) {
              console.error(e);
              console.trace();
          }
      });
  });
}

// *** Message Handler ***
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log(message, sender, sendResponse);
  switch (message.action) {
      case 'playNavigationSound':
          sendAudioMessage('playNavigationSound');
          break;
      case 'playDownloadCompleteSound':
          sendAudioMessage('playDownloadCompleteSound');
          break;
      case 'playDownloadErrorSound':
          sendAudioMessage('playDownloadErrorSound');
          break;
      case 'playMuteWarningSound':
          sendAudioMessage('playMuteWarningSound');
          break;
      case 'changeVolume':
          changeVolume(0.75);
          break;
      default:
          console.log('Unknown message action:', message.action);
  }
});

Also, here is my content-script.js code for context.

// Helper function to play audio
function playAudio(audioFile) {
    console.log(audioFile, chrome.runtime.getURL(audioFile));
    const audio = new Audio(chrome.runtime.getURL(audioFile));
    // Play the audio only when the EventListener for click is triggered
    audio.addEventListener('click', () => {
        audio.play();
    });
  }
  
  // Helper function for setting volume
  function setAudioVolume(volumeLevel) {
    const audioElements = document.querySelectorAll('audio');
    audioElements.forEach(audio => {
      audio.volume = volumeLevel;
    });
  }
  
  // Receive messages from your service worker
  chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log(message, sender, sendResponse);
    switch (message.action) {
      case 'playNavigationSound':
        playAudio('nav.ogg');
        break;
      case 'playDownloadCompleteSound':
        playAudio('complete.ogg');
        break;
      case 'playDownloadErrorSound':
        playAudio('error.ogg');
        break;
      case 'playMuteWarningSound':
        playAudio('unlock.ogg');
        break;
      case 'changeVolume':
        setAudioVolume(message.volume);
        break;
      default:
        console.log('Unknown message action:', message.action);
    }
  });

Lastly, here is my manifest.json file.

{
  "manifest_version": 3,
  "name": "PopupSound",
  "description": "Plays a click sound when you click on a link. Also plays a trumpet sound when you finish downloading a file.",
  "author": "Michael Gunter",
  "version": "3.0",
  "offline_enabled": true,
  "default_locale": "en",
  "icons": {
    "46": "icon_46.png",
    "96": "icon_96.png",
    "128": "icon_128.png"
  },
  "background": {
      "service_worker": "service-worker.js"
  },
  "content_scripts": [{
      "matches": ["<all_urls>"],
      "js": ["content-script.js"],
      "run_at": "document_end"
  }],
  "web_accessible_resources": [{
      "resources": [
          "*.ogg"
      ],
      "matches": [
          "<all_urls>"
      ],
      "extensions": []
  }],
  "permissions": [
      "webNavigation",
      "downloads",
      "tabs",
      "activeTab"
  ],
  "host_permissions": ["<all_urls>"],
  "content_security_policy": {}
}

I am so close to having the program work without any errors, but this issue is getting me stumped. I would grately appreciate your help. Please and thank you.

I tried debugging with the Chrome DevTools, but I wasn’t able to resolve my issue.

When I login to my heroku account,it is asking the code generated by authenticator app ,but I did not saved it when I login ..I can I solve this [closed]

When I login to my heroku it it is asking the code from authentication app I forget to save that code when I signup so it is getting an error when login,I now How can I get that code..

I want to login it ..I had tried it many times ,I unable to login it please any one help me to login it again , because I have to make some changes into my account please share the solutions please

How to handle elements from second domain, when using cypress

I am using cypress for my test.
After clicking on button opening new tab with other URL.
I am using this code for opening in the same tab

cy.window().then(win => {
  cy.stub(win, 'open').callsFake((url) => {
    return win.open.wrappedMethod.call(win, url, '_self');
  }).as('Open');
});

  cy.get('.card_run').click()
  cy.get('@Open').should("be.called")

Its handling my new tab, but after clicking on any element, there are shown error message, that element is missing from DOM.

Pls, help me, how I can do anything in second domain