How to access Payload after accessing the Request url

Through Selenium in the Python language, I am working on testing the website, and I was able to access the link for the Request, and I want to access the Payload. Attached is an image that shows
enter image description here

driver = webdriver.Chrome(options=option)

driver.get("https://www.example.com")

network_entries = driver.execute_script(
    "return window.performance.getEntriesByType('resource');")

       
for entry in network_entries:
    target_url = entry['name']
    if("http://fonts.googleapis.com/css?family=Open" in target_url):
        

        print("URL:", target_url)
        # need print payload !!
        #print("PAYLOAD:", payload)

I keep getting net::ERR_BLOCKED_BY_CLIENT on the console and (status) blocked on the network tab

i have this code that makes a request to fetch an array from a laravel backend, on my local server, it runs smoothly but after i hosted it, i keep getting POST error “http://127.0.0.1:8000/retrieve net::ERR_BLOCKED_BY_CLIENT”

$.post("https://vgn.srgasaswsa.com", {
                // Retrieve CSRF token from the meta tag
                _token: document.querySelector(
                    '#registrationForm [name="_token"]'
                ).value,

                // Send the value of the selected item as a parameter
                data: item.value,
            })
                .done((res) => {
                    // Loop it as options in the corresponding Local government <select>
                    $.map(res, (item) => {
                        $(local).append(
                            ` <li class="hover:bg-red-800 hover:text-white hover:font-semibold">
                            <label for="${item}" class="w-full h-fit relative" x-on:click="isFocus = false, message = '${item}'">
                                <input type="radio"
                                            name="${local.substring(1)}"
                                            id="${item}"
                                            value="${item}"
                                            class="absolute top-0 left-0 w-full h-fit opacity-0 cursor-pointer"
                                >
                                <p class="w-full h-fit py-2 text-[50px] lg:text-[1em] lg:text-base font-normal">${item}</p>
                            </label>
                        </li>`
                        );
                    });
                })
                .fail((xhr, status, error) => {
                    console.error(error);
                });```

I changed the POST url affter hosting to the hosting url, but it still showing the same error, 

this is my laravel cors
'paths' => ['api/*', 'sanctum/csrf-cookie'],

'allowed_methods' => ['*'],

'allowed_origins' => ['https://vgn.srgasaswsa.com'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => [],

'max_age' => 0,

'supports_credentials' => true,

Embed cloudflare insights including sending data with javascript

I have the following html code to embed the Cloudflare Insights javascript into my website.

<script defer src='https://static.cloudflareinsights.com/beacon.min.js' data-cf-beacon='{"token": "001e2db377654356d03acf35f1e5a"}'></script>

Because of the cookie law in the EU, I only want to load the script when someone accepts cookies. Therefore I’ve a javascript function where I load those third-party scripts only when someone accepts cookies.

How can I embed the Cloudflare Insights script including sending the data-cf-beacon data with my javascript function? My function now loads the cloudflare script, but doesn’t send the data-cf-beacon.

function BlockCookie() {
        var imported = document.createElement('script');
        imported.src = 'https://static.cloudflareinsights.com/beacon.min.js';
        document.head.appendChild(imported);  
    } ```

Why do some libraries expose methods that does the same thing, but each in sync/async context?

Some libraries exposes two methods that essentialy does the same thing, but one of them runs in async context and the other in sync context.

Some examples are: unlink from fs/promises and unlinkSync from fs; compare, compareSync, hash and hashSync from bcrypt.

Why did they choose to do this? Is there any pros and cons of using sync or async depending on the context of my application?

Issues with Scroll Triggered animation on fixed element using CSS and Javascript

I have image animation that animates as the user scrolls down the page using CSS and Javascript and I have a fixed container so that the image animates in place as the user scrolls down. Once it is at a certain spot on screen below, it switches to relevant positioning to keep it in the parent element. I am having trouble getting it to return and scroll back up when user scrolls up again.

Here is link to the page: https://6bq.107.myftpupload.com/product/black-cherry-star-tabs/

I have tried animating this different ways but needs to have the long scroll effect while image is fixed. I am thinking I need to maybe add some additional JS to be able to scroll back up once it hits the stop area. I had to change the position from fixed to relevant to get it to stop at the stop point inside the parent div.

Please, any help appreciated.

How to give each element of an array of ojects a key

If I have an array that looks like:

arr =[ { id: ‘f794’,label: ‘Blue Bird’ } ]

how do I give the element of it a key so I get

arr =["myKey":{ id: 'f794',label: 'Blue Bird' } ]

I have tried several different ways, like

arr[0]= '"myKey"' + ":" + arr[0]

which gives me

[ "myKey:[object Object]" ]

How do I get arr =["myKey":{ id: 'f794',label: 'Blue Bird' } ]

Thanks

how to get the external ip of a kubernetes service in javascript?

I’m writing an api to create game servers that run in kubernetes. I need to create an endpoint that creates a deployment and a service and then returns the service’s external ip.
I can create both succesfully and if I run kubectl get svc after hiting the endpoint I see this:

$ kubectl get svc
NAME                 TYPE           CLUSTER-IP     EXTERNAL-IP   PORT(S)           AGE
kubernetes           ClusterIP      10.96.0.1      <none>        443/TCP           3d21h
minecraft-service    LoadBalancer   10.96.172.60   localhost     25565:31683/TCP   5s

My problem is I can’t access the value under the column EXTERNAL-IP from javascript. I can’t use loadBalancer.ingress because this is for a game server, so there is no ingress created. And can’t use loadBalancer.loadBalancerIP because it’s undefined.
This is the code of my endpoint:

const express = require('express')
const k8s = require('@kubernetes/client-node')

const app = express()
const port = 3000

const kc = new k8s.KubeConfig()
kc.loadFromDefault()
const k8sApi = kc.makeApiClient(k8s.CoreV1Api)
const k8sAppsApi = kc.makeApiClient(k8s.AppsV1Api)

app.post('/api/server/', async (req, res) => {
    const deploymentDefinition = {
        apiVersion: 'apps/v1',
        kind: 'Deployment',
        metadata: {
            name: 'minecraft-deployment',
        },
        spec: {
            replicas: 1,
            selector: {
                matchLabels: {
                    app: 'game-server',
                },
            },
            template: {
                metadata: {
                    labels: {
                        app: 'game-server',
                        game: 'minecraft'
                    },
                },
                spec: {
                    containers: [
                        {
                            name: 'minecraft',
                            image: 'minecraft',
                            imagePullPolicy: 'Never'
                        },
                    ],
                },
            },
        },
    }

    const serviceDefinition = {
        kind: "Service",
        apiVersion: "v1",
        metadata: {
            name: "minecraft-service",
        },
        spec: {
            selector: {
                app: "game-server",
            },
            ports: [{
                protocol: "TCP",
                port: 25565,
                targetPort: 25565,
            }],
            type: "LoadBalancer"
        }
    }

    try {
        const createService = await k8sApi.createNamespacedService('default', serviceDefinition)
        const createDeployment = await k8sAppsApi.createNamespacedDeployment('default', deploymentDefinition)
        sleep(5000)
        const service = await k8sApi.readNamespacedService('minecraft-service', 'default')
        //console.log(createService.body.status.loadBalancer)
        // Por defecto, algunos kube-proxy y servicios solo llenarĂ¡n 'status.loadBalancer.ingress[0].ip', otros llenarĂ¡n 'status.loadBalancer.ingress[0].hostname'.
        console.log(service.body)
        //const ip = service.body.status.loadBalancer.ingress[0].ip || service.status.loadBalancer.ingress[0].hostname
        //res.json({ ip })

    } catch (error) {
        console.error(error)
        res.status(500).json({ error: error.toString() })
    }
})

console.log(service.body) prints this:

V1Service {
  apiVersion: 'v1',
  kind: 'Service',
  metadata: V1ObjectMeta {
    annotations: undefined,
    creationTimestamp: 2024-04-30T19:37:24.000Z,
    deletionGracePeriodSeconds: undefined,
    deletionTimestamp: undefined,
    finalizers: undefined,
    generateName: undefined,
    generation: undefined,
    labels: undefined,
    managedFields: [ [V1ManagedFieldsEntry] ],
    name: 'minecraft-service',
    namespace: 'default',
    ownerReferences: undefined,
    resourceVersion: '64833',
    selfLink: undefined,
    uid: '61a9ceed-6ed6-482e-b488-6c2da17fe4c4'
  },
  spec: V1ServiceSpec {
    allocateLoadBalancerNodePorts: true,
    clusterIP: '10.96.172.60',
    clusterIPs: [ '10.96.172.60' ],
    externalIPs: undefined,
    externalName: undefined,
    externalTrafficPolicy: 'Cluster',
    healthCheckNodePort: undefined,
    internalTrafficPolicy: 'Cluster',
    ipFamilies: [ 'IPv4' ],
    ipFamilyPolicy: 'SingleStack',
    loadBalancerClass: undefined,
    loadBalancerIP: undefined,
    loadBalancerSourceRanges: undefined,
    ports: [ [V1ServicePort] ],
    publishNotReadyAddresses: undefined,
    selector: { app: 'game-server' },
    sessionAffinity: 'None',
    sessionAffinityConfig: undefined,
    type: 'LoadBalancer'
  },
  status: V1ServiceStatus {
    conditions: undefined,
    loadBalancer: V1LoadBalancerStatus { ingress: undefined }
  }
}

Any idea how to do this? Thanks
By the way, I’m on Windows 11, Docker Desktop and running the Kubernetes that comes with it.

I tried sleeping after the creation of the service. Geting the service from the cluster after creating it. I tried accessing service.loadBalancer.ingress[0].ip but resulted in an error because ingress is undefined. Tried accessing service.loadBalancer.loadBalancerIP and service.loadBalancer.externalIPs but these two are undefined too. And Tried changing the version of kubernetes/client-node to 0.19 and 0.15 but all these variables remained undefined.

Custom gutenberg block doesn’t load viewScript file on the frontend even though it’s defined in blocks.json

I’ve been struggling with this for hours. I used the @wordpress/create-block package to generate a template for me to create my first block. I’ve managed to create a hero block with an image uploader etc.

However, now I’ve come to the point where I need to actually add JS to the frontend in order to make the image carousel functionality. For some reason unknown to me, my view.js file absolutely refuses to load up in the frontend.

With loading I mean doesn’t appear in HTML, and doesn’t show up in the network tab.

I’ve searched everywhere.

  • According to the docs it’s correctly defined in my blocks.json.
  • I’m not using a render_callback in my register_block_type, so I shouldn’t have to enqueue it myself manually.
  • I’ve removed and reinserted the block about 100 times thinking it was cache or whatever.

It’s just no use. The plugin directory for my custom block is right here: https://github.com/Danielvandervelden/wp-template/tree/master/wp-content/plugins/hero if you have a moment I’d very much appreciate any help in order to get this resolved.

Thank you!

Dom Purify to remove all non-breaking space

I am using dompurify for a RichText component I have. I was hoping to add in a rule that would remove all &nbps; in the string. Here is some example code:

const content = '<p style="color:blue">Hello<span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </span>world</p>' 

const customSanitizer = {
   FORBID_ATTR: ['id', 'data-react-mount', 'data-react-props-id'],
   ALLOW_DATA_ATTR: false, 
}

const cleanedContent = DOMPurify.sanitize(content, customSanitizer)

the desired result is that the value of cleanedContent equals:

<p style="color:blue">Hello world</p> 

is there anything I can add to customSanitizer to implement this?

Error into my react native code using Gesture Handler

I’m using React Native Gesture Handler into a js file and when I run the code I receive this error

ERROR [react-native-gesture-handler] Some of the callbacks in the gesture are worklets and some are not. Either make sure that all calbacks are marked as ‘worklet’ if you wish to run them on the UI thread or use ‘.runOnJS(true)’ modifier on the gesture explicitly to run all callbacks on the JS thread.

CODE:

` import * as React from ‘react’;
import { View, Text, Dimensions } from ‘react-native’;
import styles from ‘../styles/style_home’
import * as Animatable from ‘react-native-animatable’
import {Canvas, Path, Skia} from ‘@shopify/react-native-skia’;
import {curveBasis, line, scaleLinear, scalePoint} from ‘d3’;
import DataPalmas from ‘../../assets/csvjson.json’
import Gradient from ‘./Gradient’
import XAxisText from ‘./XAxisText’;
import { clamp, runOnJS, useSharedValue, withDelay, withTiming } from ‘react-native-reanimated’;
import Cursor from ‘./Cursor’
import {
Gesture,
GestureDetector,
PanGestureHandlerEventPayload,
} from ‘react-native-gesture-handler’;
import {getYForX, parse} from ‘react-native-redash’;

export default function () {
    const [showCursor, setShowCursor] = React.useState(false)
    const animationLine = useSharedValue(0)
    const animationGradient = useSharedValue({x: 0, y: 0})
    const cx = useSharedValue(0)
    const cy = useSharedValue(0)

    React.useEffect(() => {
        animationLine.value = withTiming(1, {duration:2000})
        animationGradient.value = withDelay(2000, withTiming({x: 0, y: chartHeight}, {duration: 1000}))
    }, [])

    const chartHeight = 150
    const chartWidth = Dimensions.get('window').width
    const chartMargin = 20
    const data = DataPalmas

    const xDomain = data.map((dataPoint) => dataPoint.Data)
    const xRange = [chartMargin, chartWidth - chartMargin]
    const x = scalePoint().domain(xDomain).range(xRange).padding(0)
    const stepX = x.step()
    const max = Math.max(...data.map(val => val.Precipitacao))
    const min = Math.min(...data.map(val => val.Precipitacao))

    const yDomain = [min, max]
    const yRange = [chartHeight, 0]
    const y = scaleLinear().domain(yDomain).range(yRange)

    const curvedLine = line()
    .x(d => x(d.Data))
    .y(d => y(d.Precipitacao))
    .curve(curveBasis)(data)

    const linePath = Skia.Path.MakeFromSVGString(curvedLine)
    const path = parse(linePath.toSVGString())

    function handleGestureEvent(e){
        const clampValue = clamp(
            Math.floor(e.absoluteX / stepX) * stepX + chartMargin,
            chartMargin,
            chartWidth - chartMargin,
        )
        cx.value = clampValue
        cy.value = getYForX(path, Math.floor(clampValue))
    }
    const pan = Gesture.Pan()
        .onTouchesDown(() => {
            setShowCursor(true)
        })
        .onTouchesUp(() => {
            setShowCursor(false)
        })
        .onBegin(handleGestureEvent)
        .onChange(handleGestureEvent)

    return (
    <Animatable.View style={styles.container__graphic} animation={"fadeInLeft"}>
        <GestureDetector gesture={pan}>
            <Canvas
            style={{
                width: chartWidth, 
                height: chartHeight+30,
            }}>
                <Path 
                path={linePath} 
                style={'stroke'} 
                strokeWidth={2} 
                color={'#0bb861'} 
                strokeCap={'round'}
                start={0}
                end={animationLine}/>
                <Gradient
                    chartHeight = {chartHeight}
                    chartMargin = {chartMargin}
                    chartWidth = {chartWidth}
                    curvedLine = {curvedLine}
                    animationGradient = {animationGradient}
                />
                {data.map((dataPoint, index) => (
                    <XAxisText
                        x={x(dataPoint.Data)}
                        y={chartHeight}
                        text={dataPoint.Data}
                        key={index}
                    />
                ))}
                {showCursor && 
                <Cursor 
                    cx = {cx}
                    cy = {cy}
                    chartHeight = {chartHeight}
                />}
                
            </Canvas>
        </GestureDetector>
    </Animatable.View>
    );
}`

When I use ‘worklet’ into this function the app crashes when I click

function handleGestureEvent(e){
    **'worklet'**
    const clampValue = clamp(
        Math.floor(e.absoluteX / stepX) * stepX + chartMargin,
        chartMargin,
        chartWidth - chartMargin,
    )
    cx.value = clampValue
    cy.value = getYForX(path, Math.floor(clampValue))
}

Is it possible to NOT use updated values in this method?

Apologies if I framed that question weird. Let me show you all what I mean. I am working with JavaScript classes currently.

class Car {
    constructor(name){
        this.distance = 0;
        this.fuel =  100;
        this.pedalPressure = 0;
        this.name =name;
    }

    changePedalPressure(vl){
        this.pedalPressure=this.pedalPressure+vl;
    }

    accelerate(){
        this.distance=this.distance+this.pedalPressure;
        
        this.fuel=this.fuel-Math.abs(this.distance);
    }

I have this “Car” class as well as a couple of methods paired with them. The problem is that when I call the accelerate() method/function more than once, it uses the updated values instead of using the starting ones. This is only a problem because I am trying to track the fuel attribute efficiently, and when the method uses the updated values of “this.distance” and “this.pedalPressure”, the fuel attribute gets messed up and is not accurate.

Say for example I use the starting values as defined above and call the accelerate function and lets have “pedalPressure” be 10.

const CAR = new Car("CAR")
CAR.changePedalPressure(10)
CAR.accelerate()

And log it out I would get something like:

Car {distance: 10, fuel: 90, pedalPressure: 10, name: 'CAR'}

Which is perfect, but if I call accelerate() once more after the first time and log it out I get this:

Car {distance: 20, fuel: 70, pedalPressure: 10, name: 'CAR'}

As you can see the fuel is not acting linear at all since it is using the updated values of “this.distance” and “this.pedalPressure”.

I would like to get something like this:

Car {distance: 20, fuel: 80, pedalPressure: 10, name: 'CAR'}

Is there any way I can fix it to where the fuel attribute is updated more linearly and/or doesn’t use the updated values?

I’ve tried loops, but I don’t know how I would craft it.

Apologies if this is weird. If anyone can help me with this or point me to the right page that would be amazing!

How to add Tooltip when hovering over the Total of an Apexcharts chart?

I am using ApexChart and would like to add a Tooltip when the user hovers the mouse over the Total. I have read the documentation and forums but have not been able to do it.

My code is as follows:

const chartData = {
      series: series,
      options: {
        chart: {
          selection: {
            enabled: false
          },
          height: 400,
          type: 'radialBar',
          events: {
            dataPointSelection: async function(event, chartContext, config) {
              const dataIndex = config.dataPointIndex;
              const item = chartData.options.labels[dataIndex];
              const functionId = data.function_id;

              let query = {
                date_after: filters.date_after,
                date_before: filters.date_before,
                function_id: functionId,
                keyword: item
              };

              let queryParams = buildQueryString(query);
              const { response, error } = await fetchKeyDetail(queryParams);

              if(response){
                setShowModal(true)
                setNameKey(item)
                setDetailWord(response.data.report)
                setShowText(false)
              }
            }
          }
        },
        states: {
          active: {
            filter: {
              type: 'none'
            }
          }
        },
        plotOptions: {
          radialBar: {
            hollow: {
              size: series.length > 10 ? '25%' : '50%',
            },
            dataLabels: {
              name: {
                fontSize: '14px',
                show: showText,
              },
              value: {
                fontSize: '14px',
                offsetY: 0,
              },
              total: {
                show: true,
                label: data.keywords.length === 1 ? data.keywords[0].keyword : 'Total',
                formatter: function (w) {
                  const totalValue = Math.round(parseFloat(data.conversation_prtg) * 100) / 100;
                  return totalValue;
                },
              }, 
            },
          },
        },
        labels: labels,
      },
    };

I was trying to use the ‘tooltip’ property, but that adds the tooltip when passing the mouse over each radial circle of the graphic and I need that only the tooltip is activated when I pass the mouse over the Total

tooltip: {
      enabled: true,
      shared: true,
      custom: function({ series, seriesIndex, dataPointIndex, w }) {
        const totalValue = Math.round(parseFloat(data.conversation_prtg) * 100) / 100;
        return `
          <div>
            <div>Total: ${totalValue}</div>
            <div>Additional Information: Your additional information here</div>
          </div>
        `;
      },
    },

I would be very grateful for your help.

Resuse headless puppeteer instance from PHP

I have a PHP app that needs to take some screenshots. Currently it spawns then destroys a Puppeteer/Chrome instance each time, but I want to re-use the instance to increase performance when it runs batches.

In pseudo code: script 1: launch Puppeteer, grab the instance URL/websocket address, disconnect; script2: loop over screenshots; script 3: close

My JS is letting me down I think – when it hits browser.disconnect(); it never returns to PHP as the process doesn’t complete.


Example code:

PHP: function spawn_chrome() { exec( 'node spawn_chrome.js', $command_output, $command_result ); [...] };

JS (spawn_chrome.js):

const puppeteer = require('/usr/local/lib/nodejs/node_modules/puppeteer');

(async () => {
  const browser = await puppeteer.launch({
    headless: 'shell',
    executablePath: '/usr/bin/chromium',
    args: [
      '--no-sandbox',
      [...]
      '--use-mock-keychain',
    ]
  });

  var browserWSEndpoint = browser.wsEndpoint();
  await browser.disconnect();

  console.log(browserWSEndpoint);
})();

If I replace await browser.disconnect(); with await browser.close(); the script finishes/returns. But according to the docs they both return a promise so I’m surprised they’re behaving differently.

Is my JS failing here? Or have I misunderstood it more fundamentally and you can’t disconnect and finish script processing while leaving the Chrome instance up?