How can I access information being stored on one page of my chrome extension on a separate page of my chrome extension

I’m currently working on a chrome extension and using the storage API to save inputs and values. I want the user to be able to input a goal number on the settings page and display that number on the index page. How do I go about doing this?

I’ve tried accessing the stored goal value however it comes up as null while on the index page. It is properly stored when on the settings page.

Pausing all audios HTML and JavaScript

I’m trying to create a button that, when it is clicked, it stops all the other audios from playing and plays another specific sound.

I created an array with the names of all the audios’ ids (there are just 2 right now but I’ll add others later) and i tried to iterate through it pausing all the audios (except rapstar, which needs to be played) but they keep playing.

JavaScript:

document.addEventListener('DOMContentLoaded', function() {

    const audios = ['gotg','rapstar'];

    document.getElementById('polo-g-play').addEventListener('click', function() {
      for (let i = 0, k = audios.lenght; i < k; i++) {
        if (audios[i] != 'rapstar') {
          document.getElementById(audios[i]).pause();
        }
      }
      let audio = document.getElementById('rapstar');
      if (audio.paused)
      {
        audio.play();
      }
      else
      {
        audio.pause();
      }
    }); 
  });

The part after the for loop deals with playing the audio if it is paused or pausing it if it is already playing (just like the classic spotify play button).

The HTML of the 2 audios are these:

<audio id="rapstar" src="audio/rapstar.mp3">
    No Music Here
</audio>
<audio id="gotg" src="audio/getyourlove.mp3">
    No Music Here 
</audio>

In Laravel Jetstream I cant upload a picture >2MB

I have a issue without answer. I created a new Laravel project with Jetstream and livewire stack. I dont make any modification,its fresh I just want to upload a photo profile and it work with any file less than 2mb, but not beyond it. My php.ini is well configurated with post_max_size, upload_max_filesize at 100M and 80M. My UpdateUserProfileInformation.php in app/Actions/Fortify is well configured with "'photo' => ['nullable', 'mimes:jpg,jpeg,png', 'max:10240']," It seems that a photo>2MB is directly reject when I load it with a red message "The photo failed to upload." without even be sending. I think the problem come from the input field in the update-information-form.blade.php line 41 "<x-secondary-button class="mt-2 me-2" type="button" x-on:click.prevent="$refs.photo.click()">", maybe they are something wrong with the function "$refs.photo.click()". Do you have a solution for it? I will help me and other Laravel Jetstream user.

I try to upload a profile picture in laravel jetstream but it work only with file sized less than 2MB

How to access data passed to jinija template from the webpage using javascript

I am passing a python list that contains two lists within it to a template. The code is as follows:

return render_template("result.html", result=pythonList)

where pythonList follows the structure:

[[a list of positive comments], [a list of negative comments]]

my result.html is as follows:

<div id = "commentsContainer">
</div>

<a onclick="displayPositive()">positive comments</a>
<a onclick="displayNegative()">negative comments</a>

<script>
   function displayPositive(){
      //code to assign the result[0] list to a const javascript variable called positive
      
   }
   function displayPositive(){
      //code to assign the result[1] list to a const javascript variable called negative
   }
</script>
                 

I tried to pass in the pythonList as json using

return render_template("result.html", result=json.dumps(pythonList))

but I am not sure if this is standard practice. I also dont know how to access this result json either. This is what I tried so far.

Window.open() doesn’t work in Safari in iPhone

window.open() doesn’t work in safari in iPhone.
“Doesn’t work” means it does not open a window when it is called. Nothing happens in Next.js.

It works in Safari in iPad.
It works in Safari in desktop.
It works in chrome in anywhere.
I can’t wrapper tag because url is changed according to response of backend.
This is my code.

let a = document.createElement("a");
document.body.appendChild(a);
a.setAttribute("style", "display: none");
a.href = address;
a.target = "_blank";
a.click();
document.body.removeChild(a);

Has anybody addressed this problem yet?

Postman – Async request within Test Function

I’ve been testing the asynchronous nature of the Postman sendRequest() function and I’m trying to get it working within an pm.test block but my initial efforts are failing

This is the first example to show the async nature of sendRequest()

for (let i = 1; i < 11; i++) {

    let testValue = `request${i}`

    let request = {
        url: 'https://postman-echo.com/get?test=' + testValue,
        method: 'GET',
    }

    pm.sendRequest(request, (err, res) => {
        if (err) {
            console.log(err);
        }
        pm.test(`Request ${i} - status code is 200`, () => {
            pm.expect(res).to.have.status(200);
            let resJson = res.json();
            console.log(resJson.args.test);
        });
    });

};

enter image description here

sendRequest now supports promises and top-level awaits, so this can be rectified by the following.

for (let i = 1; i < 11; i++) {
    const response = await pm.sendRequest(`https://postman-echo.com/get?test=request${i}`);

    pm.test(`Request ${i} - status code is 200`, () => {
        pm.expect(response).to.have.status(200);
        
        let resJson = response.json();
        console.log(resJson.args.test);
    });
};

enter image description here

You can add a catch for some error handing.

for (let i = 1; i < 11; i++) {
    const response = await pm.sendRequest(`https://postman-echo.com/get?test=request${i}`).catch(error => console.log(error));
    pm.test(`Request ${i} - status code is 200`, () => {
        pm.expect(response).to.have.status(200);
        let resJson = response.json();
        console.log(resJson.args.test);
    });
};

or

for (let i = 1; i < 11; i++) {
    try {
        const response = await pm.sendRequest(`https://postman-echo.com/get?test=request${i}`);
        pm.test(`Request ${i} - status code is 200`, () => {
            pm.expect(response).to.have.status(200);
            let resJson = response.json();
            console.log(resJson.args.test);
        });
    } catch (error) {
        console.log(error);
        pm.test(`Request ${i} - status code is 200`, () => {
            pm.expect(error, error.code).to.be.undefined;
        });
    }
};

Other versions that produce pretty much the same result.

const sendRequest = (req) => {
    return new Promise((resolve, reject) => {
        pm.sendRequest(req, (err, res) => {
            if (err) {
                console.log(err);
                return reject(err);
            }
            resolve(res);
        });
    });
};

(async () => {
    for (let i = 1; i < 11; i++) {
        let testValue = `request${i}`
        let request = {
            url: 'https://postman-echo.com/get?test=' + testValue,
            method: 'GET',
        }
        const response = await sendRequest(request); // wait for promise to be resolved before continuing
        pm.test(`Request ${i} - status code is 200`, () => {
            pm.expect(response).to.have.status(200);
            let resJson = response.json();
            console.log(resJson.args.test);
        });
    }
})();
const sendRequest = (req) => {
    return new Promise((resolve, reject) => {
        pm.sendRequest(req, (err, res) => {
            if (err) {
                console.log(err);
                return reject(err);
            }
            resolve(res);
        });
    });
};

async function asyncCall(request, i) {
    const response = await sendRequest(request);
    pm.test(`Request ${i} - status code is 200`, () => {
        pm.expect(response).to.have.status(200);
        let resJson = response.json();
        console.log(resJson.args.test);
    });
};

for (let i = 1; i < 11; i++) {
    let request = {
        url: 'https://postman-echo.com/get?test=' + `request${i}`,
        method: 'GET',
    }
    await asyncCall(request, i);
};

The final version I ended up with.

async function sendRequest(request, i) {
    try {
        const response = await pm.sendRequest(request);
        pm.test(`Request ${i} - status code is 200`, () => {
            pm.expect(response).to.have.status(200);
        });
        return {
            'data': response,
            'status': "success"
        };
    } catch (error) {
        console.log(error);
        pm.test(`Request ${i} - status code is 200`, () => {
            pm.expect(error, error.code).to.be.undefined;
        });
        return {
            "status": "error",
            "errorcode": error.code
        }
    }
};

for (let i = 1; i < 11; i++) {
    let response = await sendRequest(`https://postman-echo.com/get?test=request${i}`, i);
    if (response.status === "success") {
        console.log(response.data.json().args.test); // Postman Echo Response
    }
};

What I really want to do though is move the async sendRequest into the test block.

So if the request fails, it stops processing any more code

If you do the following, you get a syntax error.

for (let i = 1; i < 11; i++) {

    pm.test(`Request ${i} - status code is 200`, () => {
        const response = await pm.sendRequest(`https://postman-echo.com/get?test=request${i}`);
        pm.expect(response).to.have.status(200);
        let resJson = response.json();
        console.log(resJson.args.test);
    });

};

SyntaxError: await is only valid in async functions and the top level bodies of modules

If you do the following, it no longer errors, but the requests are no longer in order either.

for (let i = 1; i < 11; i++) {

    pm.test(`Request ${i} - status code is 200`, async () => {
        const response = await pm.sendRequest(`https://postman-echo.com/get?test=request${i}`);
        pm.expect(response).to.have.status(200);
        let resJson = response.json();
        console.log(resJson.args.test);
    });

};

Searching the Internet, I stumbled across the following.

https://jestjs.io/docs/asynchronous

So I then looked at the Postman docs which seems to indicate that its using the Mocha framework under the hood.

https://github.com/postmanlabs/postman-runtime/tree/develop/test

Another Internet Search later.

https://masteringjs.io/tutorials/mocha/async

This seems to indicate that I should be able to do something like I’m trying, but although I can get the code to run without errors, it’s never in order anymore.

Can someone please push me in the right direction on what I’m doing wrong here.

Shopware 6: Custom translations in en-GB.json not overriding default snippets

I’m having trouble overriding default Shopware 6 snippets with my custom translations in a plugin. Despite defining custom translations in my en-GB.json file, the default values are still being displayed.

Here’s my en-GB.json file:

{
    "sw-customer": {
        "baseInfo": {
            "labelBoundSalesChannel": "Bound Sales Channel",
            "emptyBoundSalesChannel": "None"
        }
    }
}

And here’s the relevant part of my Twig template (sw-customer-base-info):

{% block sw_customer_base_metadata_bound_sales_channel %}
    <sw-description-list>
        {% block sw_customer_base_metadata_bound_sales_channel_label %}
            <dt class="sw-customer-base-info__label sw-bound-sales-channel__label">
                {{ $tc('sw-customer.baseInfo.labelBoundSalesChannel') }}
            <sw-help-text :text="$tc('sw-customer.baseInfo.helpTextBoundSalesChannel')" />
        </dt>
    {% endblock %}
    {% block sw_customer_base_metadata_bound_saleschannel_content %}
        <dd class="sw-customer-base__label-bound-sales-channel">
            <template v-if="customer.boundSalesChannelId">
                {{ customer.salesChannel.translated.name }}
            </template>
            <template v-else>
                {{ $tc('sw-customer.baseInfo.emptyBoundSalesChannel') }}
            </template>
        </dd>
    {% endblock %}
</sw-description-list>
{% endblock %}

I expected to see ‘Bound Sales Channel’ as the label for labelBoundSalesChannel and ‘None’ for emptyBoundSalesChannel. However, I’m seeing ‘Sales Channel’ and ‘All’ respectively, which are the default values.

What am I missing? How can I get my custom translations to override the default snippets?
Environment:

Shopware version: [6.6.4.1]
PHP version: [8.2]

How to print zpl in web via javascript?

I have a zebra label printer. I am attempting to print labels for fun using javascript and webUSB.

The current setup prints blank labels.

Here is the excerpt:

// Get USB device (the zebra printer)
const printer = await navigator.usb.requestDevice({
  filters: [],
});
await printer.open();
await printer.selectConfiguration(deviceConfiguration);
await printer.claimInterface(interfaceNumber);

// Hello world print command
const source = `^XA
^FO100,80
^FDHello, World!^FS
^XZ
`;

// Send print command - Method 1
const encoded = new TextEncoder().encode(source);
await printer.transferOut(1, encoded); // 1 is the endpoint number. 1 is the only valid value for my printer. We can get this from the printer (type:USBDevice) object.
// => When executed, prints a blank label.

// Send print command - Method 2
const blob = new Blob([source], {
  type: "text/plain",
});

const arrayBuffer = await blob.arrayBuffer();
await printer.transferOut(1, arrayBuffer);
// => When executed, prints a blank label.

Can someone help me understand what am I doing wrong?

In the zpl documentation, they say:

Save the file as a .txt file and copy it to the printer from DOS command line.

enter image description here

I am attempting to find the equivalent in web.

Update: I don’t want to use 3rd party libraries. I’m attempting to understand the low level fundamentals.

Demo: https://github.com/vajahath/label-jet

ECharts: Candlestick width not increasing on zoom with time xAxis and ’empty’ filterMode

Using ECharts, I’ve noticed that candlesticks don’t widen when zooming in with these settings:

  1. xAxis type is ‘time’
  2. dataZoom filterMode is ’empty’
  3. Series type is ‘candlestick’
var option = {
    xAxis: { type: 'time' },
    yAxis: { type: 'value', scale: true },
    series: [{
        type: 'candlestick',
        data: ohlcData,
    }],
    dataZoom: [{
        type: 'inside',
        xAxisIndex: [0],
        filterMode: 'empty',
    }, {
        type: 'slider',
        xAxisIndex: [0],
        filterMode: 'empty',
    }]
};

Full example: https://codepen.io/xpatt/pen/RwzZwYR

How can I make candlesticks widen on zoom while keeping the ‘time’ xAxis and ’empty’ filterMode?

How to ‘polyfill’ `interactive-widget=resizes-content` for meta viewport tag on iOS Safari?

Chrome added support for interactive-widget=resizes-content in v108, and Firefox seems to support this as of writing. But I’ve tested up to iOS Safari 17.4 and it doesn’t seem to support it.

Is there some way to ‘polyfill’ this, ideally in versions iOS Safari v15, onwards?

Related:

Dynamically add color in ion-card text based on regex

I want to add a span around some text when a # or a @ is detected so I can change the color to make it look like usernames and hashtags in twitter. My code looks like this:

TS FILE:

ngOnInit(): void {
    this.glyphService.getAllGlyphs().subscribe(
      result => {
        this.items = result;
        // sort by rune id so list is newest to oldest
        this.items.sort((a, b) => Number(b.rune) - Number(a.rune));
        for (let i = 0; i < this.items.length; i++) {
          this.items[i].glyph_content = this.replaceIt(this.items[i].glyph_content);
          console.log(this.items[i])
        }
        console.log(this.items)
      }
    );
  }

  replaceIt = (str: string) => {
    const regex = /B([#@][a-zA-Z]+b)(?!;)/g;
    const subst = `<span style="color:blue">$1</span>`;
    const result = str.replace(regex, subst);
    return result;
 }

HTML FILE:

  <ion-card *ngFor="let item of items" >
    <ion-card-header>
      <ion-card-title>&#64;{{item.username}}</ion-card-title>
      <ion-card-subtitle>{{item.glyph_date}}</ion-card-subtitle>
    </ion-card-header>
    <ion-card-content>
      {{item.glyph_content}}
    </ion-card-content>
 </ion-card>

I’m successfully replacing the text like I want to, however it’s just winding up as text instead actual tags and looks like this:
test <span style="color:blue">@hey</span> <span style="color:blue">@uh</span> wow <span style="color:blue">#ah</span> words <span style="color:blue">#oh</span>
Is there a way for me to change my code so I’m actually dynamically wrapping the target text in real spans like I want? Is it possible to use *ngIf in some creative way here?

Creating a polygon with a texture in Phaser 3 Matter js

In Phaser 3 (using matter JS physics), it seems that there’s no way of setting a texture to a polygon, and yet I need to have a hexagon/pentagon with a texture.

I’ve been unable to figure out how to set a PNG texture of a polygon with the physics of a polygon. How can I do this?

I’ve already figured out the vertices of a needed polygon, but cannot find a way to create it with a texture attached

const pentagonVertices = [  
  { x: (0) +0.5, y: ((2.01 / 4) + 0.5) },
  { x: (1.91 / 4) + 0.5, y: ((0.62 / 4) + 0.5) }, 
  { x: (1.18 / 4) + 0.5, y: ((-1.63 / 4) + 0.5) },
  { x: (-1.18 / 4) + 0.5,y: ((-1.63 / 4) + 0.5) },
  { x: (-1.91 / 4) + 0.5,y: ((0.62 / 4) + 0.5) }
];

I tried this:

const polygon = globalThis.add.polygon(worldPosX, worldPosY, pentagonVertices, 0x8d8d8d); 
var poly = globalThis.add.image(worldPosX, worldPosY, 'image', polygon);
globalThis.matter.add.gameObject(poly);
const polygon = globalThis.add.polygon(worldPosX, worldPosY, pentagonVertices, 0x8d8d8d); 
var poly =  globalThis.matter.add.gameObject(polygon); poly.setTexture('image')  //setTexture is not defined for some reason
globalThis.matter.add.gameObject(poly);

ag grid compared with angular mat table: DOM structure

I work with ag grid table and Angular 14.
I have a doubt that ag grid add more div or more something in DOM compared with Angular material table.
i can use that command in console with * or with class or id to calculate the number of elements.

document.querySelectorAll('*').length;

My question is : which one add more div in the dom if i use the same number of row and column.

Invoking W3Schools CodeColor library on multiple elements

I want to offer code examples and I am using a JS code highlighter with an ID. See this URL for the working demo: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_syntax_highlight

I want to use this for multiple examples but the ID only works once. I have tried both ID and Class but this still doesn’t work.

w3CodeColor(document.getElementById("myDiv")); // only works for 1 element
w3CodeColor(document.getElementByClassName("myDiv")); // does not work

The example code what I have tried is below,

<div class="myDiv">code example goes here</div>
<div id="myDiv">code example goes here</div>

Any help would be much appreciated, thanks

What is the difference between destructuring and and just using properties in React

I have some problems regarding React code. Inside my App.jsx, I wrote the logic with and without the destructuring of an object I get from an jsx tag:


<input
   name="fName"
   placeholder="First Name"
   onChange={handleChange}
   value={fullName.fName}
/>
<input
   name="lName"
   placeholder="Last Name"
   onChange={handleChange}
   value={fullName.lName}
/>

Here is the code with destructuring way:


function handleChange(event) {
    const { name, value } = event.target;

    setFullName((preValue) => {
      if (name === "fName") {
        return {
          fName: value,
          lName: preValue.lName,
        };
      } else if (name === "lName") {
        return {
          fName: preValue.fName,
          lName: value,
        };
      }
    });
  }

While this is the code without destructuring way


function handleChange(event) {
    setFullName((preValue) => {
      if (event.target.name === "fName") {
        return {
          fName: event.target.value,
          lName: preValue.lName,
        };
      } else if (event.target.name === "lName") {
        return {
          fName: preValue.fName,
          lName: event.target.value,
        };
      }
    });
  }

Note that I tried to write the code with the same logic. However, while the former does work, in the latter way, my code doesn’t work and starts to crash showing this error:

TypeError
Cannot read properties of null (reading 'name')
eval
/src/components/App.jsx:11:23
   8 | 
   9 | function handleChange(event) {
  10 |   setFullName((preValue) => {
> 11 |     if (event.target.name === "fName") {
     |                     ^
  12 |       return {
  13 |         fName: event.target.value,
  14 |         lName: preValue.lName,


I expect it to work even when I do not use the destructuring