Chrome extension content script not being injected sometimes

I have a chrome extension for fillling forms on certain websites. This all works well, however sporadically the content script for filling the form doesn’t get injected anymore, then I have to reinstall the extension to remediate the problem. This is the code I use for injecting the content script:

chrome.tabs.create({ url: url, active: true }, function (tab) {  //create tab
    chrome.tabs.onUpdated.addListener(function listener(tabId, info) {
        if (info.status === 'complete' && tabId === tab.id) {
            chrome.tabs.onUpdated.removeListener(listener);               
                chrome.tabs.executeScript(tab.id, { file: 'library.js', allFrames: true, runAt: "document_end" }, function () {                        
                    chrome.tabs.executeScript(tab.id, { file: marketPlace + '.js', allFrames: true, runAt: "document_end" }, function () {
                        //inject content script
                        chrome.tabs.sendMessage(tab.id, { formData });  //send message to content script
                    });
            });
        }
    });
});

I suppose it’s some kind of a timing issue or something that changed in the Chrome api? Because the problem only occured recently.

How can I make Apexchart y-axis label and data label format different?

hello what i want to do is to have axis label as decimal number such as 1M, 2M
and have data label as money format such as $11,111,111.
I tried

labels: {
      formatter: function(val) {
        return '$' + val.toLocaleString('en-US');
      }
    }

axisLabel: {
      formatter: function(val) {
        return '$' + val.toLocaleString('en-US');
      }
    }

I tried either or both at the same time but axis label and data label always changes together..
is it possible to have different format for axis label and data label?

thank you!

How to apply the same js function to multiple div id

I have four div id elements (and I cannot switch id for class) and I need the same javascript function to work for all of them, not just the first one. The function shuffles the verses of the poem everytime the page is refreshed, and it only works for the first div so far, I don’t know how to repeat it for the others. I already tried copy pasting it four times and changing the variable names and I also tried “document.getElementById(‘text1,text2,etc..’)” both methods made the code stop working completely. Any suggestions? Thanks!

const text = document.getElementById('text1');

function rndPoem() {

  const lines = text
  .innerHTML.split(/<br>/)
  .map(line => line.trim());

  for (let i = lines.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [lines[i], lines[j]] = [lines[j], lines[i]];
  }

  return lines.join('<br>');

}
text.innerHTML = rndPoem();
    html {
     
    }
    body {
          font-family: 'Arial';
         font-size: 10px;
      font-family: 'Arial';
      display: flex;
      font-size: 1vw;
      text-transform: uppercase;
      line-height: 1;
      overflow: hidden;
      margin-left: 5%;
        margin-right: 10%;
    }

.text {
    padding: 2%;
    width: 25%;
}
<div id="text1">

  Quand le ciel bas et lourd pèse comme un couvercle<br> Sur l'esprit gémissant en proie aux longs ennuis,<br> Et que de l'horizon embrassant tout le cercle<br> Il nous verse un jour noir plus triste que les nuits ;<br> Quand la terre est changée en un
  cachot humide,<br> Où l'Espérance, comme une chauve-souris,<br> S'en va battant les murs de son aile timide<br> Et se cognant la tête à des plafonds pourris ;<br> Quand la pluie étalant ses immenses traînées<br> D'une vaste prison imite les barreaux,<br>  Et qu'un peuple muet d'infâmes araignées<br> Vient tendre ses filets au fond de nos cerveaux,<br> Des cloches tout à coup sautent avec furie<br> Et lancent vers le ciel un affreux hurlement,<br> Ainsi que des esprits errants et sans patrie<br> Qui se
  mettent à geindre opiniâtrement.<br> - Et de longs corbillards, sans tambours ni musique,<br> Défilent lentement dans mon âme ; l'Espoir,<br> Vaincu, pleure, et l'Angoisse atroce, despotique,<br> Sur mon crâne incliné plante son drapeau noir.<br>
</div>
<div id="text2">

  Quand le ciel bas et lourd pèse comme un couvercle<br> Sur l'esprit gémissant en proie aux longs ennuis,<br> Et que de l'horizon embrassant tout le cercle<br> Il nous verse un jour noir plus triste que les nuits ;<br> Quand la terre est changée en un
  cachot humide,<br> Où l'Espérance, comme une chauve-souris,<br> S'en va battant les murs de son aile timide<br> Et se cognant la tête à des plafonds pourris ;<br> Quand la pluie étalant ses immenses traînées<br> D'une vaste prison imite les barreaux,<br>  Et qu'un peuple muet d'infâmes araignées<br> Vient tendre ses filets au fond de nos cerveaux,<br> Des cloches tout à coup sautent avec furie<br> Et lancent vers le ciel un affreux hurlement,<br> Ainsi que des esprits errants et sans patrie<br> Qui se
  mettent à geindre opiniâtrement.<br> - Et de longs corbillards, sans tambours ni musique,<br> Défilent lentement dans mon âme ; l'Espoir,<br> Vaincu, pleure, et l'Angoisse atroce, despotique,<br> Sur mon crâne incliné plante son drapeau noir.<br>
</div>
<div id="text3">

  Quand le ciel bas et lourd pèse comme un couvercle<br> Sur l'esprit gémissant en proie aux longs ennuis,<br> Et que de l'horizon embrassant tout le cercle<br> Il nous verse un jour noir plus triste que les nuits ;<br> Quand la terre est changée en un
  cachot humide,<br> Où l'Espérance, comme une chauve-souris,<br> S'en va battant les murs de son aile timide<br> Et se cognant la tête à des plafonds pourris ;<br> Quand la pluie étalant ses immenses traînées<br> D'une vaste prison imite les barreaux,<br>  Et qu'un peuple muet d'infâmes araignées<br> Vient tendre ses filets au fond de nos cerveaux,<br> Des cloches tout à coup sautent avec furie<br> Et lancent vers le ciel un affreux hurlement,<br> Ainsi que des esprits errants et sans patrie<br> Qui se
  mettent à geindre opiniâtrement.<br> - Et de longs corbillards, sans tambours ni musique,<br> Défilent lentement dans mon âme ; l'Espoir,<br> Vaincu, pleure, et l'Angoisse atroce, despotique,<br> Sur mon crâne incliné plante son drapeau noir.<br>
</div>
<div id="text4">

  Quand le ciel bas et lourd pèse comme un couvercle<br> Sur l'esprit gémissant en proie aux longs ennuis,<br> Et que de l'horizon embrassant tout le cercle<br> Il nous verse un jour noir plus triste que les nuits ;<br> Quand la terre est changée en un
  cachot humide,<br> Où l'Espérance, comme une chauve-souris,<br> S'en va battant les murs de son aile timide<br> Et se cognant la tête à des plafonds pourris ;<br> Quand la pluie étalant ses immenses traînées<br> D'une vaste prison imite les barreaux,<br>  Et qu'un peuple muet d'infâmes araignées<br> Vient tendre ses filets au fond de nos cerveaux,<br> Des cloches tout à coup sautent avec furie<br> Et lancent vers le ciel un affreux hurlement,<br> Ainsi que des esprits errants et sans patrie<br> Qui se
  mettent à geindre opiniâtrement.<br> - Et de longs corbillards, sans tambours ni musique,<br> Défilent lentement dans mon âme ; l'Espoir,<br> Vaincu, pleure, et l'Angoisse atroce, despotique,<br> Sur mon crâne incliné plante son drapeau noir.<br>
</div>

Print DYMO label from web app – need help to print remotely

My web app has label printing capability added using DYMO Label framework JavaScript library.

It works fine on my computer(both localhost and remote) where DYMO label software is installed and a shared DYMO printer is added.

Now, when I try to access the same web app from other device, dymo code does not work. It says “no DYMO printers are installed” and dymo code does not generate label preview or display printer name etc.. Looks like each device need to have DYMO label software installed and printer added, for it to work.

So my question is, do each client machine need to have Dymo label software installed? in order for the web app to allow printing label. I believe there has to be a way around. Any help would be appreciated.

dymo.connect.framework.js
Software Installed: DYMO Label Software 8.7.4
Connected to printer: DYMO LabelWriter 450

Is it possible to create an empty array as an object property?

I’d like to create an object constructor function that gives each object that it creates its own array property like so:

function objectCreator(name, arr) {
    this.name = name;
    this.arr = [];

    return {name,arr}
}

Eventually I’ll take data in from a form and then push the data into each own object that I’ve created. I’m getting an error that says the array is undefined since it is empty. How would I go about declaring an empty array inside of an object that I can add data into it? Hope my question makes sense

Apollo useQuery() throws Error: ECONNREFUSED when running async test in React Testing Library

  • React 16.4.0
  • Apollo Client 3.5.9
  • React Testing Library 12.1.2

I’m having chronic issues with testing React components that call Apollo useQuery() when they mount. If I use async RTL methods, the GraphQL query fails with an ECONNREFUSED error. If I use sync RTL methods I do not get this error. However, sync methods do not work because the assertion runs while loading equals true. Therefore, the data has not come back from the query and thus there is no content to render.

Here is a code snippet from a test that elicits this error:

it('renders', async () => {
  renderGrid()
  const columnHeading = await screen.findByText(/Primary Household Member/i)
  expect(columnHeading).toBeInTheDocument()
})

I have attached a screenshot of what this produces in the console (see below).
If I change the code to be synchronous like so:

it('renders', () => {
  renderGrid()
  const columnHeading = screen.getByText(/Primary Household Member/i)
  expect(columnHeading).toBeInTheDocument()
})

I do not get the ECONNREFUSED error. However, in that case, loading is true and data and error are undefined. I cannot test that the grid rendered the table because in this case, the component simply returns <div>loading...</div>. I have tried wrapping the render function in act() but this does not change anything. I have also tried waitFor() to no avail.

I will include the full code for the test. Please note that I am writing some data to the client-side cache. This is because in addition to making the network request, the component fetches some local state by querying properties with the @client directive.

Here is the full content of the test file. It is followed by the console screenshot:

import React from 'react'
import { render, screen } from 'Utils/test-utils'
import {
  GET_INDIVIDUAL_DEMOGRAPHICS,
  GET_REPORTING_GRID_SETTINGS,
  GET_COLUMN_SELECTIONS,
  GET_REPORTING_MODAL_STATE,
} from 'Components/Reporting/Hooks/gql'
import mockCache, {
  reportingIndividualDateRangeStartVar,
  reportingIndividualDateRangeEndVar,
} from 'ApolloClient/caseManagementCache'
import {
  apolloMocks,
  mockReportingGridState,
  mockReportingColumnsData,
  mockReportingModalsData,
} from './fixtures'
import ReportingGrid from './ReportingGrid'
import getColumnsData from 'Components/CaseManagement/Reporting/Grids/Demographics/Individual/columnsData'

// Set dateRanges in the cache to match the values used in the Apollo mocks
beforeEach(() => {
  // Set dateRanges in the cache to match the values used in the Apollo mocks
  reportingIndividualDateRangeStartVar('2022-01-01T05:00:00.000Z')
  reportingIndividualDateRangeEndVar('2022-06-03T13:56:36.662Z')

  mockCache.writeQuery(
    {
      query: GET_REPORTING_GRID_SETTINGS,
      data: mockReportingGridState,
    },
    {
      query: GET_COLUMN_SELECTIONS,
      data: mockReportingColumnsData,
    },
    {
      query: GET_REPORTING_MODAL_STATE,
      data: mockReportingModalsData,
    }
  )
})

const renderGrid = () => {
  render(
    <ReportingGrid
      dataQueryTag={GET_INDIVIDUAL_DEMOGRAPHICS}
      defaultSortField={'fullName'}
      getColumnsData={getColumnsData}
      sortable
      pageable
      reportEnum={'INDIVIDUAL'}
    />,
    {
      apolloMocks,
      cache: mockCache,
      addTypename: true,
    }
  )
}

it('renders', () => {
  renderGrid()
  const columnHeading = screen.getByText(/Primary Household Member/i)
  expect(columnHeading).toBeInTheDocument()
})

enter image description here

React.js doesn’t display fetched image from Django

My component successfully fetches info (texts and images) from the Django backend but fails to display the images.

related: react.js doesn’t display fetched image

I removed file 192png from manifest.js and HTML and it didn’t work so I put them back again as advised.

import React, { useState, useEffect, Fragment} from 'react';
import axios from 'axios';
import Carousel from 'react-elastic-carousel';
import './Schools.css';
import Test from '../assets/images/back.jpg';

const schoolBreakPoints = [
    {width: 1, itemsToShow: 1 },
    {width: 550, itemsToShow: 2 },
    {width: 768, itemsToShow: 3 },
    {width: 1200, itemsToShow: 4 },
];

function Schools() {
    const [languageCenters, setLanguageCenters] = useState ([]);

    useEffect(() => {
        const config = {
            headers: {
                'Content-Type': 'application/json'
            }
        };

        const getLanguageCenters = async () => {
            try {
                const res = await axios.get(`${process.env.REACT_APP_API_URL}/api/partners/list/`, config);
                setLanguageCenters(res.data);
            }
            catch (err) {

            }
        };

        getLanguageCenters();
    }, []);

    const getAllLanguageCenters = () => {
        let allLanguageCenters = [];
        let results = [];

        languageCenters.map(languageCenter => {
            console.log(languageCenter.photo)
            return allLanguageCenters.push(
                <Fragment key={languageCenter.id}>
                    <div className='school__display'>
                        <img className='school__display__image' src={languageCenter.photo} alt='school logo' />
                    </div>
                    <h3 className='school__language__center'>{languageCenter.name}</h3>
                    <p className='school__course'>{languageCenter.country}</p>
                    <p className='school__course'>{languageCenter.language}</p>
                    <p className='school__course'>{languageCenter.course}</p>
                    <p className='school__about'>{languageCenter.note}</p>
                </Fragment>
            );
        });

        for (let i = 0; i < languageCenters.length; i += 20) {
            results.push(
                <div key={i} className='school__card__row'>
                    <Carousel breakPoints={schoolBreakPoints}>
                        <div className='school__card'>
                            {allLanguageCenters[i]}
                        </div>
                        <div className='school__card'>
                            {allLanguageCenters[i+1] ? allLanguageCenters[i+1] : null}
                        </div>
                        <div className='school__card'>
                            {allLanguageCenters[i+2] ? allLanguageCenters[i+2] : null}
                        </div>
                        <div className='school__card'>
                            {allLanguageCenters[i+3] ? allLanguageCenters[i+3] : null}
                        </div>
                        <div className='school__card'>
                            {allLanguageCenters[i+4] ? allLanguageCenters[i+4] : null}
                        </div>
                    </Carousel>
                </div>
            );
        }

        return results;
    };  

  return (
    <div className='schools'>
        <section className='schools__language__centers'>
            <div className='schools__row'>
                <h2 className='schools__subheading'>Language Centers</h2>
            </div>
            {getAllLanguageCenters()}
        </section>
    </div>
  )
}

export default Schools

developer tool > all ;

developer tool > all

developer tool > img ;

developer tool > img

And below is what I see on the browser, only the broken icon and the rel ;

on browser

React Next.js: getServerProps is not returning array from prisma

Background

After learning getServerProps, I tried building a project that returns some data from postgres using prisma, but for some reason, when I try to map the posts array ( See below ), it returns the array as undefined. Enevn I believe I followed syntax rules on the Doc page, no luck so far. I have been stuck for long time and I don’t know why and what i did wrong. At least VS code recognize posts as array, but getServerProps function seems it never gets run.Thanks for reading, lemme know your thoughts on this.

Summary of my problem

  • I don’t know why the array (posts variable) is undefined when it is recognized inside of the function.
  • I don’t know why getServerProps seems to be not called

Note:

Prisma and postgres are working in this project

import { PrismaClient } from '@prisma/client'
function Posts({ posts }) {

return (
  <div>
    <h1 className="text-4xl block text-gray-500 font-bold pt-5 text-center">
      Posts
    </h1>
    <div>
      {posts.map((post) => {
        <h3>{post.title}</h3>;
      })}
    </div>
  </div>
);
}

export const getServerSideProps = async () => {
    const prisma = new PrismaClient()
    const posts = await prisma.post.findMany()

    
    return { props: { posts } }
  }

export default Posts

Error I get:
Error Message

Label of input field disappears after cycling through select options

I’m having a problem when a label of input field disappears after cycling through select options. On the first try it shows “c” but then when I cycle through it it disappears. Where could be the problem? Thanks =)

Relevant code:

<select class="form-control" onchange="izborLik()" id="izbor"> 
<option value="1">Pravokutnik</option>
<option value="2">Kružnica</option>
<option value="3">Pravokutni trokut</option>
</select>

<label id="natpis1" for="polje1">A:</label>
            <input class="form-control" id="polje1" type="number">
            <label id="natpis2" for="polje2">B:</label>
            <input class="form-control" id="polje2" type="number">
            <label id="natpis3" for="polje3">C:</label>
            <input class="form-control" id="polje3" type="number"><br>


 function izborLik() {

            let val = document.getElementById("izbor").value;
            let lik;
            var p1 = document.getElementById("polje1");
            var p2 = document.getElementById("polje2");
            var p3 = document.getElementById("polje3");
            var n1 = document.getElementById("natpis1");
            var n2 = document.getElementById("natpis2");
            var n3 = document.getElementById("natpis3");
            n1.innerHTML = "a";
            n2.innerHTML = " "
            if (val == 1) {
                n1.innerHTML = "a";
                n2.innerHTML = "b";
                n3.style.display = "none";
                p1.value = "5";
                p2.value = "10"
                p2.style.display = "inline-block";;
                p3.style.display = "none";
            } else if (val == 2) {
                n1.innerHTML = "r";
                n2.innerHTML = " ";
                n3.innerHTML = " ";
                p1.value = "10";
                p2.style.display = "none";
                p3.style.display = "none";
            } else if (val == 3) {
                n1.innerHTML = "a";
                n2.innerHTML = "b";
                n3.innerHTML = "c";
                p1.value = "";
                p2.value = "";
                p3.value = "";
                p1.style.display = "inline-block";
                p2.style.display = "inline-block";
                p3.style.display = "inline-block";
            }
        }

Updating react element at the same time HTML element updates?

I currently have a window that pops up when a button (checkbox) is clicked, where the window and checkbox are html elements in index.html. I also have a button (with complicated features) coded in a .tsx file, that I would like to have pop up when the previously mentioned window pops up.

In my CSS file, I simply have the following to get the window pop-up effect when clicking the checkbox:

.content{
  visibility: hidden;
}

#click:checked ~ .content{
  visibility: visible;
}

Additionally, I can easily show and hide the button from the .tsx file, in the CSS file as follows:

.btn{
  visibility: hidden/visible;
}

Effectively, all I want is to have

.content{
  visibility: hidden;
}

.btn{
    visibility: hidden;
}

#click:checked ~ .content{
  visibility: visible; /* make pop-up window visible */

  .btn{
    visibility: visible; /* make button visible within same trigger */
  }

}

that is, have the button hidden by default, then when the window opens after clicking the checkbox, have the button change to visible. This has been surprisingly difficult to find a solution for; I would really appreciate any help.

Graphql React: Missing field ‘editParentCat’ while writing result true

So, I am trying to update category data using useMutation hook in react. The fields I am going to mutate are name, description with it’s associated id. But whenever I send mutation I got Missing field 'editScat' while writing result true error. Here is my code.

const [categoryName, setCategoryName] = useState("");
  const [categoryDescription, setCategoryDescription] = useState("");
  const [categoryId, setCategoryId] = useState("");
 const EDIT_SUB_CATEGORY = gql`
    mutation editScat($id: UUID!, $name: String!, $description: String!) {
      editScat(id: $id, name: $name, description: $description) {
        payload {
          id
          name
          description
        }
      }
    }
  `;
  const [updateCatMutation] = useMutation(EDIT_SUB_CATEGORY);
  const updateMe = (e) => {
    e.preventDefault();
    updateCatMutation({
      variables: {
        id: categoryId,
        name: categoryName,
        description: categoryDescription,
      },

      optimisticResponse: true,
    })
      .then((res) => {
        alert("Success");
      })
      .catch((err) => {
        alert("Failed");
      });
  };

enter image description here

What did I missed here?

How can I write these js codes with for loop?

I have 3 buttons and 3 content.
When I click on any button, I want to show the content of that button. When I click on the other button, I want to show the content of that button and delete the content of the other button.

I managed to do this with simple logic, but how can I do it with a for loop?

photo

const content = document.querySelectorAll('.content');
const contentClose = document.querySelector('.close-content');
const btnsOpenContent = document.querySelectorAll('.show-content');


btnsOpenContent[0].addEventListener('click',
function(){
    content[1].classList.remove('show-modal');
    content[2].classList.remove('show-modal');
    content[0].classList.add('show-modal');
}
)

btnsOpenContent[1].addEventListener('click',
function(){
    content[0].classList.remove('show-modal');
    content[2].classList.remove('show-modal');
    content[1].classList.add('show-modal');
}
)

btnsOpenContent[2].addEventListener('click',
function(){
    content[0].classList.remove('show-modal');
    content[1].classList.remove('show-modal');
    content[2].classList.add('show-modal');
}
)

Add class to parent based on the button value – Pure Javascript

On click of button I want to pass the data-value to the parent class.
If 2 button are clicked both the class will be added to the parent, and when re-click on the same button again then remove the class based on the data-value

I have jquery version but can anyone help in pure javascript

<div class="parent">
  <button data-value="first">Button 1</button>
  <button data-value="middle">Button 1</button>
  <button data-value="last">Button 1</button>
</div>
<script>

</script>

Scorm player – setting a progress bar as complete

I’m taking a drivers ed course which uses Scorm player and is painfully slow – it requires a progress bar to fill before I can progress to the next slide which often takes 2-3x as long as I need to read it. I’ve used inspect element to try to understand how the progress bar works and how I can set it to complete once I finish the slide. Here is what it shows in inspect element:

<div tabindex="-1" aria-hidden="false" aria-label="slide progress" data-ref="progressBar" class="cs-fill cs-brandhighlight-bg progress-bar-fill" style="width: 100%;" role="slider" aria-valuemin="0" aria-valuenow="23.04" aria-valuemax="23" data-tabindex="-1" aria-valuetext="100%">
        <div class="prev-progress-bar-fill-preview cs-fill" data-ref="prevProgressPreview"></div>
      </div>

So, my question: is there a way I can set the progress bar to complete in the console to allow me to progress to the next slide?