chrome.action.onClicked not working when adding “default_popup” in manifest

I am starting to learn building chrome extension. I want to execute some code when the extension is clicked. But I also need to have a html popup to show when the extension is clicked.

I added this code to background.js

chrome.action.onClicked.addListener((tab) => {
  console.log(tab);
});

and in the manifest.json file, if I keep this "default_popup" attribute, I don’t get a console.log

"action": {
  "default_title": "Some Title",
  "default_popup": "index.html"
},

If I remove the "default_popup" attribute and click the extension I get a console.log with the active tab object.

But I want both, I want to show the html popup (index.html) and execute my script.

Is it possible somehow?

The script I want to execute when the extension is clicked will be like –

chrome.action.onClicked.addListener((tab) => {
  chrome.tabs.sendMessage(tabId, msg)
});

I want to send message to the content script when the extension is clicked.

I tried adding the below code in the popup.js but it gives error – Could not establish connection. Receiver end does not exist.

chrome.tabs.query({ active: true, lastFocusedWindow: true }).then((tab) => {
  chrome.tabs.sendMessage(tab[0].id, "GET_TITLE").then((response) => {
    console.log("Got response:", response);
  });
});

I do have the listener code in my content.js file –

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  sendResponse("Acknowledgment of your message");
});

Thank you.

multiple languages ​in express.js

I would like to add the option of multiple languages ​​to my website (express.js and ejs) both by location and in the settings. Does anyone know how to do this? Thank you in advance

Tried searching github, youtube but couldn’t find anything

What is the difference in the calls to “this” in nested XMLHttpRequest()?

I’m new to JavaScript and have run into an issue in calling the XMLHttpRequest function.

My code is as follows:

document.addEventListener('load', loadJsonFile(), false);

function reqListener() {
    var obj = JSON.parse(this.responseText)

    //Send for the html of a generic post
    var reqObj = new XMLHttpRequest();
    reqObj.onload = buildProjects(reqObj, obj);
    reqObj.open("get", "post_box.html", true);
    reqObj.send();
}

function buildProjects(reqObj, data){

    for(var i = 0; i < 5; i++){
        

        html = reqObj.responseText;
        console.log("data is: " + data.title);
        console.log("State: " + this.readyState);
        console.log("Request object is: " + reqObj);
        console.log("Response is: " + reqObj.response);
        console.log("html is: " + html);
    }
}

//Load all project data
//Then call reqListener function
function loadJsonFile(){
    var reqObj = new XMLHttpRequest();
    reqObj.onload = reqListener;
    reqObj.open("get", "test.json", true);
    reqObj.send();
}

I expected calling ‘this’ in the buildProjects() function would return the calling XMLHttpRequest object. This does not happen. Instead a ‘Window’ object is returned.

I tried working around this by passing the reqObj as parameters but this doesn’t work either. I’m guessing this is a scope issue ?

I don’t have any idea why the call to ‘this’ doesn’t work. Calling ‘this’ works for me when I have a single XMLHttpRequest.onload function called, so I’m led to thinking it’s something to do with nesting a request within a request ?

I’ve seen a similar question asked regarding functions called using arrow notation but I can’t see how the answer there answers my problem.

Help is appreciated,

Thanks

How can I send stream data via API to Nuxt3 application?

Hello I’m stuck in making an API to return chunked data to Nuxt3 frontend in realtime. I’m actually trying to implement streaming of ChatGPT API responses that this git codes achieve for Next.js in my Nuxt3 app.

https://github.com/shivanshubisht/chatgpt

The following is the data flow which I’m trying to make happen.

(a) Nuxt3 frontend <-> (b) Wrapper API running on nitro for Nuxt3 <-> (c) ChatGPT API Handler on nitro <-> (d) ChatGPT API

Environment: “nuxt”: “^3.2.3”, Windows 11, node.js 16

I have a problem with data transfer between (b) wrapper and (c) handler, while (c) handler itself perfectly works to pull stream data from ChatGPT API in realtime. There seems an issue with either/both (c) to return the same chunked data that it received from ChatGPT or/and (b) to receive the data from (c) in stream. I guess that both have issue, though.

Here are the codes that I think have some problems:

(b) Wrapper API: /server/api/response.post.ts

import { OpenAIStream, OpenAIStreamPayload } from '@/server/api/openaistream'

type RequestData = {
  currentModel: string
  message: string
}

export default defineEventHandler(async (event) => {
  const { message } = await readBody(event);

  const payload: OpenAIStreamPayload = {
    model: 'gpt-3.5-turbo',
    messages: [{ role: 'user', content: message }],
    temperature: 0.7,
    top_p: 1,
    frequency_penalty: 0,
    presence_penalty: 0,
    max_tokens: 500,
    stream: true,
    n: 1,
  }

  const stream = await OpenAIStream(payload);
  return new Response(stream);
})

(c) ChatGPT handler: /server/api/openaistream.ts

import {
  createParser,
  ParsedEvent,
  ReconnectInterval,
} from 'eventsource-parser';

export type ChatGPTAgent = 'user' | 'system';
export interface ChatGPTMessage {
  //abbreviated
}
export interface OpenAIStreamPayload {
  //abbreviated
}

export async function OpenAIStream(payload: OpenAIStreamPayload) {
  const encoder = new TextEncoder();
  const decoder = new TextDecoder();

  let counter = 0;

  const res = await fetch('https://api.openai.com/v1/chat/completions', {
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${process.env.OPENAI_API_KEY ?? ''}`,
    },
    method: 'POST',
    body: JSON.stringify(payload),
  });

  const stream = new ReadableStream({
    async start(controller) {
      // callback
      function onParse(event: ParsedEvent | ReconnectInterval) {
        if (event.type === 'event') {
          const data = event.data;
          // https://beta.openai.com/docs/api-reference/completions/create#completions/create-stream
          if (data === '[DONE]') {
            console.log("END!");
            controller.close();
            return;
          }
          try {
            const json = JSON.parse(data);
            const text = json.choices[0].delta?.content || '';
            // check if it receives chunked data from chatgpt API
            console.log(text);
            if (counter < 2 && (text.match(/n/) || []).length) {
              // this is a prefix character (i.e., "nn"), do nothing
              return;
            }
            const queue = encoder.encode(text);
            controller.enqueue(queue);
            counter++;
          } catch (e) {
            // maybe parse error
            controller.error(e);
          }
        }
      }

      for await (const chunk of res.body as any) {
        //check if it can decode the chunk data to send as stream data
        console.log(decoder.decode(chunk))
        parser.feed(decoder.decode(chunk));
      }
    },
  });

  return stream;
}

I guess that h3/nitro for Nuxt3 might work differently in handling stream data from Next.js/Vercel but I can’t figure out how it should work because of very few resources. Could anyone please share any thoughts or suggestion? Thank you!

The API handler properly sends chunked stream data to another API running on nitro in realtime.

Vuetify and css to show svg image on the side on bigger screen

I am trying to make my forms more attractive, by adding a picture on the right hand side if there are space.
I am working with vuetify, and typically want to do this when using component.

I would prefer this to be easy to use.
Therefore I decided my images will always be displayed as 200px width.

I have two solutions, but I am sure there must be a better way to handle this!

Solution 1:

<v-card class="ma-2 pa-2">
  <v-icon> 2A     </v-icon>
  <v-card-title class="ma-2">
     side image SHOWING IMAGE in last v-col - hide on smaller than md
  </v-card-title>
  <v-card-text class="mr-5 ma-2 " >
  <v-row>
    <v-col cols="11" sm="11" md="9" lg="8"
           class="right-side-line">
     <v-text-field label="This Label" append-icon="mdi-kettle" />
     <v-text-field label="Another Label" prepend-inner-icon="mdi-kettle" />
     <v-text-field label="Width" v-model="w" />
     <v-text-field label="Height" v-model="h" />
     vbp-mdAndUp{{ $vuetify.breakpoint.mdAndUp }}
     vbp-lgAndUp{{ $vuetify.breakpoint.lgAndUp }}
     <span class="ma-2">{{ this.$vuetify.breakpoint.name }} </span>
    </v-col>
   <v-col v-if="$vuetify.breakpoint.mdAndUp" cols="1" md="3" lg="4"
          class="thebox">
   </v-col>
  </v-row>
  </v-card-text>
  <v-card-actions> <v-btn> Click Me </v-btn> <v-spacer/>  <v-btn> Or Click Me </v-btn> </v-card-actions>
</v-card>

Above is a bit nasty, and is such a lot of work to get something simple to work
(Will include styling below)

Solution 2

<v-card class="ma-2 pa-2" :class="$vuetify.breakpoint.mdAndUp ? 'thebox' : ''" elevation="-6" >
  <v-icon> 4B </v-icon>
  <v-card-title class="ma-2 "> rightside line and thebox in card (sol 4A) </v-card-title>
  <v-card-text class="right-side-line" :style="$vuetify.breakpoint.mdAndUp ? 'padding-right:290px' : ''">
    <v-text-field label="This Label" append-icon="mdi-kettle" />
    <v-text-field label="Another Label" prepend-inner-icon="mdi-kettle" />
    <v-text-field label="Width" v-model="w" />
    <v-text-field label="Height" v-model="h" />
    vbp-mdAndUp{{ $vuetify.breakpoint.mdAndUp }}
    vbp-lgAndUp{{ $vuetify.breakpoint.lgAndUp }}
    <span class="ma-2">{{ this.$vuetify.breakpoint.name }} </span>
  </v-card-text>
  <v-card-actions> <v-btn> Click Me </v-btn> <v-spacer/>  <v-btn> Or Click Me </v-btn> </v-card-actions>
</v-card>

Solution 2 has js code on v-card, and js code on v-card-text, this is to check size of screen. I believe I should be able to get this working with just a simple class name on my v-card

Something like or 🙂

Styling used:

div.thebox
{
  box-sizing: border-box;
  /* see : https://stackoverflow.com/questions/4694191/how-do-i-add-margin-to-just-background-image
  */
  padding-right: 5px;
  background-image: url('~@/img/GreenStripe.svg');
  background-size: contain;
  background-repeat: no-repeat;
  background-origin: content-box;
  background-position: right;
}

.zaside {
  flex-direction: row-reverse;
  flex: 200px;
  background-position: right;
  background-repeat: no-repeat;
  background-size: contain;
  background-image: url('~@/img/GreenStripe.svg');
  margin-right: 20px;
}
.right-side-line {
    background-image: linear-gradient(to right,black 33%,rgba(255, 255, 255, 0) 0%);
    background-position: right;
    background-size: 3px 1px;
    background-repeat: repeat-y;
}

reading this before posting… I guess media query is the answer?
however – any help and feedback would be great!
From – The CPT City Turtle

ps. I tried about 8 other options, that is why css “zaside” is included.

express-fileupload request.files is always undefined

I want to upload a file from my browser and POST it to an Express.js application that then downloads the file using express-fileupload.
Client-side javascript code so far:

// fires on onclick event of a button
function upload() {
    // only get one file (you also only can select one in the input field)
    file = document.getElementById('file').files[0]

    // check if a file is selected
    if (file.length == 0) {return}

    // add file to a form
    form = new FormData()
    form.append('file', file)

    // POST form using fetchAPI
    fetch('/upload', {
        headers: {
            'Content-Type': 'multipart/form-data'
        },
        method: 'POST',
        body: form
    })
}

The client code completes without any errors. The request even shows up on my network-tab.
The request from the client arrives at this controller:

import express from 'express'
import fileUpload from 'express-fileupload'

export function uploadPOST(req: express.Request, res: express.Response) {
    if (req.files) {
        console.log('put')
        const file: fileUpload.UploadedFile = req.files.file as fileUpload.UploadedFile
        file.mv(`${settings.storage.path}/${req.app.get('username')}/${file.name}`)
    }
}

In the debugger, req.files is always undefined but the application throws no errors.
I also added fileUpload and bodyParser.json() to my middleware.

Other people got the same problem and posted it but the answers didn’t resolve my case.
I also followed this tutorial: https://attacomsian.com/blog/uploading-files-nodejs-express

Script dictate to correct text mistakes

I’m locking for a java script that is able to evaluate dictate Text after hearing it from audio; I found a similar website that offer this script, but I can’t see the content of the source code reviewing source code for instant in google chrome.

example:
https://dailydictation.com/exercises/short-stories/1-first-snowfall.1/listen-and-type
enter image description here

as you can see after typing Check, November is incorrectly written an highlighted.

it will great full if someone could help to create such fragment code with this GUI in codepen. I’m completely newbie in HTML/CSS/JS.

GUI HTML interface to correct dictate text.

Execute group of promises or cancel them all

My question is how we grauntee the exection of group of promises in JavaScript?
I have 3 promises, one for deleting user profile picture, one for deleting user cover image and last one for deleting the user object and his information.

What I need to handle, that if one promise is rejected, I should cancel excetion of the others.
As it won’t be logic to delete, for example, the user image however, his info didn’t be deleted.

Any suggestions?

Text as button with styled components

I try to make a text as button with react native with styled components.

So I have this:

import { Button } from "react-native";
import styled from "styled-components/native";

export const ButtonCol = styled(Button)`
    backgroundcolor: red;
    color: white;
    border: 0;  
    
`;

and the component:


export const CategoryInfoCard = ({ category = {} }) => {
    const {
        name = "Zoogdieren",
        images = "https://cdn.pixabay.com/photo/2017/02/20/18/03/cat-2083492_960_720.jpg",
        icon = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSE3_hmm2zWrH4ZLUoqEr4FUb5f-BIn9_c5Qg&usqp=CAU",
        detail = "Detail",
    } = category;

    return (
        <CategoryCard
            elevation={5}
            style={{
                borderTopLeftRadius: 0,
                borderTopRightRadius: 0,
                borderBottomLeftRadius: 0,
                borderBottomRightRadius: 0,
            }}>
            <Text variant="caption" style={{ left: 100 }}>
                {name}
            </Text>
            <CategoryGroupCardCover source={{ uri: images }} />
            <Card.Actions>
                <ButtonCol title="ok" variant="text" />
            </Card.Actions>

        </CategoryCard>
    );
};

But nothing changed. With this I mean I see a blue rectangele with oke in it.

Question: how to make text as a button?

Fixed an item of Stack mui in scrolling

Hi guys there is a problem that I want to set the position of an item fixed to when scrolling just center Item scroll and left item remains fixed how can I do this?

<Stack direction={`row`} spacing={10} divider={<Divider orientation={`vertical`} color={`black`} flexItem/>}>
                    <Item>leftside</Item>
                    <Item> center</Item>
</Stack>

I already try position css field and it didn’t work

How can I create a Net Salary Calculator using JavaScript, CSS and HTML

Net Salary Calculator (Toy Problem)
Write a program whose major task is to calculate an individual’s Net Salary by getting the inputs of basic salary and benefits. Calculate the payee (i.e. Tax), NHIFDeductions, NSSFDeductions, gross salary, and net salary.
NB: Use KRA, NHIF, and NSSF values provided in the link below.

https://www.aren.co.ke/payroll/taxrates.htmLinks to an external site.

https://www.kra.go.ke/en/individual/calculate-tax/calculating-tax/payeLinks to an external site.

How to get the coordinates of Selenium Mouse cursor Python without involving any elements

I need to find a way to get location coordinates of current Selenium ActionChains invisible cursor.

I can find it after I move to an element, and calculate it from size of element and location of element, but this requires to move first to it and is not very accurate.

I can find it injecting javascript to make a div on the cursor to make it visible, and thereby even getting the location of that element, but this is not ideal because it requires that I modify the webpage’s html.

How can I achieve this?

Why don’t javascript files work when deployed to web hosting?

I’m practicing downloading a production website, then uploading the website files to a web hosting service. But there is a problem with javascript files.

I used httrack to download the website, but unfortunately it doesn’t download some javascript files, no matter what configurations I’ve changed.
So, I downloaded the js files manually (through chrome network tab save as) and added the script tags manually to all html pages, and everything works like a charm. But, when I uploaded the website to 000webhost, javascript files DON’t WORK, although it’s been UPLOADED correctly.
My questions:
1 – Why js files not work? How to fix the problem? Or,
2 – How to let httrack download those js files correctly?
(the website is: www.classcentral.com)