Access website’s localStorage from the chrome extension [duplicate]

I already have a website which records the screen and based on if you’re logged in or out you can extend the recording time. Now I’m kinda developing the same logic in the chrome extension but I want to access the website’s localStorage to get the profile and check if user is logged in or no because I want the user to have the same accessibilities they have in the website e.g. the max. recording time etc…

I’m using manifest v3
So I was wondering if there’s a way to access it without opening a tab?

If you need more info I’m here, Thank you!

I already tried opening the tab when we load the extension but I dont think it’s a really good user experience, and also saw somewhere that if a user is using an adblocker then things might not work with this solution.

Getting a translation dynamically based on lang attribute [duplicate]

Im trying to add simple translations by utilizing the lang attribute.

Given the following:

var currentLang = document.documentElement.lang;
const translations = {
    en: {
        hello: "Hello World",
    },
    es: {
        hello: "Hola Mundo",
    },
};

Why does this work

console.log(translations.en.hello)

but not this

console.log(translations.currentLang.hello)

Im sure theres something simple im missing, but I cant figure out what. Thanks for any help in advance.

Why is my function to call javascript file not working in wordpress plugin?

I’m trying to add a function inside my php file, which is inside an /admin/ folder, to call a specific javascript file, roomzeroadmin.js.
I’ve tried using:

function roomzero_load_admin_scripts() {
    // Enqueue admin.js for the admin dashboard
    wp_enqueue_script(
        'roomzero-admin-script', // Unique handle
        plugin_dir_url(__FILE__) . 'js/roomzeroadmin.js', // Path to admin.js
        array('jquery'), // Dependencies (if any)
        '1.0.0', // Version
        true // Load in footer
    );
}
add_action('admin_enqueue_scripts', 'roomzero_load_admin_scripts');

but it just doesn’t seem to work. I also tried

add_action('wp_enqueue_scripts','roomzero_js');

function roomzero_js() {
    wp_enqueue_script( 'roomzero-test-js', plugins_url( '/js/roomzero.js', __FILE__ ));
}

but that doesn’t work either. Any suggestions on how I can make this work?

CSV exportGrid file data not clearing between dijit.byId options

I’ve coded a pair of tabs (User Inbox and Group Inbox) that are to save their respective, tabled page content as a CSV and export the data to Excel. The problem is after initially exporting the User Inbox content (containing a handful of rows) successfully, and then exporting the Group Inbox content (containing the data of both tabs) successfully, a subsequent attempt to export the User Inbox (during the same session) sends the data of both tabs, instead on the handful of rows exported the first time.

It almost seems like a buffer needs to be part of the code to clear any buffer/data after each tab has its proper CSV records exported. And doing a Shift/browser refresh doesn’t clear the issue up. Didn’t know if there were any thoughts?

on(dom.byId(“exportGrids”), “click”, function(){
var exportData;

    //6 rows        
    dijit.byId("userInboxGrid").exportGrid("csv", function(gridData) {
        exportData = gridData;
        dom.byId("exportData").value = exportData;
    });
    
    //the 6 rows of the User Inbox tab + those of the Group Inbox tab
    dijit.byId("groupInboxGrid").exportGrid("csv", function(gridData) {
        exportData = exportData + gridData;
        dom.byId("exportData").value = exportData;
    }); 

    return true;
});

Thnks,
Dave

How to receive data from client-side of websocket in Django using Channels

I’m trying to receive a websocket message on the server side. It is not being received. Am I misusing the function? How should this function be implemented as to receive messages and have the 30s live updates running in parallel.

I have created a web server using Django Channels (Daphne) in Python.

It is sending data async to the client via a websocket to live-update charts created using chart.js every 30 seconds. This all works fine.

However, when the user makes a selection and a graph changes, I need new data to be sent immediately. So I’m trying to make a request: the client sends a request to the server via the websocket, the server then receives said request and sends data back to the client.

My problem is, that the websocket is not receiving any data from the client, although everything seems to be alright. Am I misunderstanding how the functions are to be used? Any help will be appreciated!

There are no errors in the log or console, neither server- nor client-side.

See the code for my AsyncWebsocketConsumer:

from asyncio import sleep
from channels.generic.websocket import AsyncWebsocketConsumer
from func.web_read import DatasetBuilder
from datetime import datetime, timedelta, timezone


class ChartDraw(AsyncWebsocketConsumer):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._dataset: str
        self._hash_dataset: hash
        self._allmeasurements: DatasetBuilder

    async def connect(self):
        await self.accept()

        self._allmeasurements = DatasetBuilder(1) # some magic, building a dataset

        self._date_end: datetime = datetime.now(timezone(timedelta(hours=+1)))
        self._date_start: datetime = self._date_end - timedelta(minutes=15)
        self._dataset = self._allmeasurements.get_relevant_messages(self._date_start, self._date_end) # gets all the data from a db in the given timeframe.
        self._hash_dataset = hash(str(self._dataset))
        await self.send(str(self._dataset))

        await self.updateDataIfChanged()

    async def updateDataIfChanged(self):
        while True:
            self.updateDate()
            self._dataset = self._allmeasurements.get_relevant_messages(self._date_start, self._date_end)
            if self._hash_dataset != hash(str(self._dataset)):
            await self.send(str(self._dataset))
            self._hash_dataset = hash(str(self._dataset))
            await sleep(30)
            print("30s passed.")

    async def receive(self, text_data):
        print("New Message!")
        print(text_data)

And in the javascript these are the relevant parts:

const socket = new WebSocket('ws://localhost:8000/ws/draw_chart/');

console.log("sending to websocket ...");
try {
     socket.send("DO YOU HEAR ME!?");
} catch (error) {
     console.error("Received error sending data to websocket:", error)
}

It seems there is very little useful documentation on this. I tried to use async.gather to execute receive and my function “updateDataIfChanged” in parallel but to no avail.

As I then realized receive runs in parallel anyways and listens for messages I reverted it back. Shouldn’t it output the received text as soon as it is received?

useState returns nothing on fetch [duplicate]

I’m fetching sidebar items of an external page that isn’t mine, so I have a fetch. Inside that fetch I get the sidebar, and the forEach function is to get all the sidebar’s <a> elements. The title property running this in console log works fine, fetches me what I want, but when I want to store those items in a useState returns nothing – console.log(sidebarBrands) returns an empty array.
What am I doing wrong here?

import React, { useEffect, useState } from 'react'

function Main() {
  const [sidebarBrands, setSidebarBrands] = useState([])
  useEffect(() => {
    fetch("https://www.gamingcity.com.ar/listado/computacion/_FiltersAvailableSidebar?filter=BRAND").then(function (response) {
      return response.text();
    }).then(function (html) {
        var parser = new DOMParser();
        var doc = parser.parseFromString(html, 'text/html');
    
        var div = doc.querySelectorAll(`[class="ui-search-search-modal-filter ui-search-link"]`);
        div.forEach((div) => {
            console.log(div.title); //this returns me titles fine, like i want
            setSidebarBrands(div.title) //then i store the titles
            console.log(sidebarBrands) // then the arrays are empty for no reason!!!
        })
    
    }).catch(function (err) {
        console.warn('algo salio como el culo', err);
    });
  }, [])

  return (
    <>
      {Array.isArray(sidebarBrands) && sidebarBrands?.length > 0 ? 
        (sidebarBrands.map(e => <SidebarBrands item={e} />)) 
        : <p>nada que mostrar</p>}
    </>
  )
}

export default Main

function SidebarBrands(props){
  const { item } = props
  return(
    <>
      <div>
        <p>{item}</p>
      </div>
    </>
  ) 
}

I dont want to show NOWW a element, the problem here IS NOT RETURNING ANYTHING, THANKS!!!

How to import openpgp.js in Deno?

As OpenPGP.js hasn’t published in JSR yet, I need to import it via HTTP if I don’t want to clone it to my local. Using:

import 'https://unpkg.com/browse/[email protected]/dist/openpgp.js';

yields:

error: Expected a JavaScript or TypeScript module, but identified a Unknown module. Importing these types of modules is currently not supported.

It does publish on deno.land/x, but using:

import 'https://deno.land/x/[email protected]/mod.js';

yields “Module not found”.

My ultimate goal is to upload Google API credentials on GitHub, via encrypting and decrypting the credentials.

Yarn Install Request failed “304 Not Modified”

error Error: https://registry.npmjs.org/emojis-list/-/emojis-list-3.0.0.tgz: Request failed “304 Not Modified”
at ResponseError.ExtendableBuiltin (/usr/local/lib/node_modules/yarn/lib/cli.js:696:66)
at new ResponseError (/usr/local/lib/node_modules/yarn/lib/cli.js:802:124)
at Request. (/usr/local/lib/node_modules/yarn/lib/cli.js:66750:16)
at Request.emit (node:events:517:28)
at module.exports.Request.onRequestResponse (/usr/local/lib/node_modules/yarn/lib/cli.js:142287:10)
at ClientRequest.emit (node:events:517:28)
at HTTPParser.parserOnIncomingClient (node:_http_client:700:27)
at HTTPParser.parserOnHeadersComplete (node:_http_common:119:17)
at TLSSocket.socketOnData (node:_http_client:541:22)
at TLSSocket.emit (node:events:517:28)
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

Its working well on my local environment but getting this error in aws production

Error `Request failed “304 Not Modified”` when running `yarn create` with Sanity CLI on Windows 11

I’m encountering the following issue when trying to run yarn create to set up a Sanity project:

PS C:UsersmalanDesktopProgramming ShitMern Projectsyc_directory> yarn create sanity@latest --project wl1d7zqt --dataset production --template clean --typescript --output-path studio-yc_directory
yarn create v1.22.22
warning package.json: No license field
[1/4] Resolving packages...
[2/4] Fetching packages...
error Error: https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz: Request failed "304 Not Modified"
    at ResponseError.ExtendableBuiltin (C:UsersmalanAppDataRoamingnpmnode_modulesyarnlibcli.js:696:66)
    at new ResponseError (C:UsersmalanAppDataRoamingnpmnode_modulesyarnlibcli.js:802:124)
    at Request.<anonymous> (C:UsersmalanAppDataRoamingnpmnode_modulesyarnlibcli.js:66750:16)
    at Request.emit (node:events:513:28)
    at module.exports.Request.onRequestResponse (C:UsersmalanAppDataRoamingnpmnode_modulesyarnlibcli.js:142287:10)
    at ClientRequest.emit (node:events:513:28)
    at HTTPParser.parserOnIncomingClient (node:_http_client:710:27)
    at HTTPParser.parserOnHeadersComplete (node:_http_common:117:17)
    at TLSSocket.socketOnData (node:_http_client:552:22)
    at TLSSocket.emit (node:events:513:28)
info Visit https://yarnpkg.com/en/docs/cli/create for documentation about this command.

My environment:

  • Operating System: Windows 11
  • nvm version: 1.1.12
  • Node.js version: v23.4.0
  • npm version: 11.0.0
  • Yarn version: 1.22.22

Things I’ve tried so far:

  • Clearing the Yarn cache (yarn cache clean)
  • Deleting and reinstalling Node.js entirely

Despite these efforts, I continue to face the same issue. Any suggestions on how to fix this or what else I could try?

Update:
I also tried switching to a different version of Node.js using nvm, but the issue persists.

Thanks in advance for your help!

Why is my S3-hosted image not showing in the PDF generated using kendo.drawing, while a direct image URL works fine?

I’m using kendo.drawing to generate a PDF that includes an image from Amazon S3, but the image doesn’t display in the generated PDF. However, when I use a direct image URL (like this one), the image shows up fine.

Here are the details:
Working Image URL (from CDN):
https://cdn.redandblue.com/ogx/web/images/logo-alt-b.png

S3 Image URL:
https://s3.amazonaws.com/officegx/Dev/394eaf7e-d62e-49ff-9434-8ee5e690ae7f/logos/8f6a289f-5198-464a-8a55-0cffcb7f09fd-638693276419413618-image1.jpg

The S3 image works fine in the browser, but when I try to embed it in the PDF, it doesn’t display.

What I’ve Tried:
Verified that the image is publicly accessible by checking the S3 object permissions.
The S3 URL is HTTPS and correctly formatted.
I’ve tested the S3 URL in the browser, and the image loads fine.
I’ve also tried configuring CORS for my S3 bucket to allow cross-origin requests.

Here is the function I’m using for PDF download:

function getPDF(data) {
    let selector = $(data).parent().parent().parent()[0];
    kendo.drawing.drawDOM($(selector)).then(function(group) {
        kendo.drawing.pdf.saveAs(group, "@fileName");
        $(".print").show();
        $("#showBankDetails").show();
    });
}

Can anyone suggest why the image doesn’t appear in the PDF and how I can fix it?

SolidJS Router – Component of Route not being displayed

My page is not being updated (components are not being rendered) according to their paths using Solid-Router.

My Header has buttons to navigate to different routes (using useNavigate hook). On clicking the buttons, the route is updated in the search bar but the component to be displayed for the particular path is not being shown. It is only displayed on reloading the page.

For example, on first opening the page. The header along with ‘Hi’ is displayed. On clicking the button to navigate to ‘/mybooks,’ ‘Hi’ is still displayed on the page (but the route is updated in the search bar). I have to reload the page on ‘/mybooks’ to get the Books component to be displayed.

My App.jsx :

function App() {
  return (
    <div class={styles.App}>
      <Header styles={styles} />
      <main>
        <Router>
         <Route path="/" component={() => <p>Hi!</p>} />
         <Route path="/mybooks" component={Books} />
         <Route path="/add" component={Add} />
        </Router>
      </main>
    </div>
  );
}

My index.jsx :

render(() => (
  <Router root={App} />
), root);

I also have links to navigate to the different pages in my Add & Books components :
Add.jsx :

<A href="/mybooks">Books</A>
<A href="/">Home</A>

Books.jsx :

<A href="/add">Add</A>
<A href="/">Home</A>

If I click ‘Books’ link on my ‘Add’ page, it takes me to the Books page. But if I click on the ‘Add’ or ‘Home’ link after that on my Books page, it doesn’t take me anywhere.

Also, my Header has buttons that change color depending on which page the user is currently on (using useLocation hook) but it doesn’t change color when I navigate using the links in my Add and Book pages.
It only changes color when navigating using the buttons (or links) in the Header (but that only updates the path and doesn’t cause any change to the page).

What should I do to be able to navigate through my webpage and get the appropriate components to display according to the path? I also want the buttons in the header to respond even when the links on the pages are used to navigate through the page. I want to navigate through the webpage (get components to be displayed according to the path) using the buttons on my header too.

Can I use condition rendering inside another condition?

So my this is what I am trying to do..

  • If there are no unread messages, display “You’re all caught up!”
  • If there’s exactly 1 unread message, it should read “You have 1 unread message”
  • If there are > 1 unread messages, display “You have unread messages
return (
  <div>
  {
    {messages.length} > 1 ?
      <h1>You have {messages.length} unread messages!</h1> : 
      {{messages.length} === 0 ? 
         <p>You have no unread messages</p> : 
         <p>You have 1 messages</p> 
      }
    }
  }
</div>
);