TypeError: Cannot read properties of null (reading ‘image’)

I am making an e-commerce website & I have no idea why I am getting this type error. I am trying to retrieve items from the cart that I stored in the local Storage but the items are coming back null. I’ve built this app multiple times for practice & I never had this problem in the past so I’m a little confused.

CartScreen.js

import {getCartItems} from "../localStorage";

const CartScreen = {
    render: async () => {
        const cartItems = getCartItems();
        return `
            ${
                cartItems.countInStock === 0
                ? `<div>Nothing is here <a href="/#/">Go Shopping</a></div>`
                : cartItems.map((item) => `
                    <li>
                        <div class="cart-image">
                            <img src="${item.image}"/>
                        </div>
                        <div class="cart-name">
                            <div>
                                <a href="#/product/${item.product}">
                                    ${item.name}
                                </a>
                            </div>
                            <div>
                                <select class="qty-select" id="${item.product}">
                                    <option value="1">1</option>
                                </select>
                                <button class="fw primary" id="${item.product}">
                                    Delete
                                </button>
                            </div>
                        </div>
                        <div class="cart-price">
                            ${item.price}
                        </div>
                    </li>
                `).join('n')
            }
                   
        `
    }
}

I know the problem is coming from the cartItems variable but when I console.log() it I get this:

enter image description here

As you can see it says there are 5 items in the cart but they are all null, Which is strange because yesterday they weren’t, now all of a sudden they are null.

Here is my localStorage.js:

export const getCartItems = () => {
    const cartItems = localStorage.getItem('cartItems') ?
    JSON.parse(localStorage.getItem('cartItems')) : [];
    return cartItems;
}

export const setCartItems = (cartItems) => {
    localStorage.setItem('cartItems', JSON.stringify(cartItems));
}

Does anyone know what’s going on here? A little help would appreciated

Angular Interceptor Implementation

so I am trying to implement an interceptor for my little app which is standalone: true, and all I want this interceptor to do is check that if the response from the server comes back with error 401 to log user so for that I wrote code with some console.logs to track it
auth.interceptor.ts

import { inject, Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse, HttpErrorResponse } from '@angular/common/http';
import { Observable, catchError, throwError } from 'rxjs';
import { Router } from '@angular/router';
import { AuthService } from '../shared/services/auth.service';

@Injectable({
  providedIn: 'root',
})
export class AuthInterceptor implements HttpInterceptor {
  private authService = inject(AuthService)
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log('Interceptor called', req);
    return next.handle(req).pipe(
      catchError((error: HttpErrorResponse) => {
        if (error.status === 401) {
          this.authService.logout(); 
        }
        return throwError(error);
      })
    );
  }
}

my app.config.server.ts looks like that

import { mergeApplicationConfig, ApplicationConfig } from '@angular/core';
import { provideServerRendering } from '@angular/platform-server';
import { appConfig } from './app.config';

const serverConfig: ApplicationConfig = {
  providers: [
    provideServerRendering()
  ]
};

export const config = mergeApplicationConfig(appConfig, serverConfig);

app.config.ts

import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app-routing.module';
import { HTTP_INTERCEPTORS, provideHttpClient, withFetch } from '@angular/common/http';
import { provideAnimations } from '@angular/platform-browser/animations';
import { AuthInterceptor } from './interceptor/auth.interceptor';
export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes),
    provideAnimations(), 
    provideHttpClient(withFetch()),
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true}
  ]
};

main.server.ts

import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { config } from './app/app.config.server';

const bootstrap = () => bootstrapApplication(AppComponent, config);

export default bootstrap;

main.ts

import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';

bootstrapApplication(AppComponent, appConfig).catch(err => console.error(err));

but problem is that I can’t even see this console.logs which I have in interceptor like interception is not even being called

I tried code above but its not working. (standalone: true)

30+ useState in a component [closed]

I need to make a form which has 4 parts that are co related with each other. Some input fields are depended on other fields. This form has radio, input, dropdown and some buttons are like prebuild variables that will fill in the field without spaces to perform mathematical operations. Along with, it has too many handler which are performing different mathematical task or destructuring from the value from drop down and many more. How do I handle or refactor too many useState?

I need a solution in which all the states can become one or atleast very that I can handle them easily. along with other things as well

WooCommerce fields in checkout page keep resetting back to their initial values – issue

I am building a JS address lookup plugin for the WooCommerce WordPress plugin, and for some reason, the shipping address values populated by the lookup plugin keep resetting back to their original values.

Video: https://www.youtube.com/watch?v=PJf_JZfuR48&ab_channel=MartinStanik

I am getting stuck with the options/ideas of what is wrong with the code. However, it seems to me that the difficulty of integrating the JS plugin in WooCommerce started in the WP platform version 6.6.

I am running my testing environment on the default WooCommerce UI template locally by Local (host, ref. https://localwp.com/) Version 9.1.0+6719.

Any idea what’s wrong?
WordPress 6.6.2
WooCommerce 9.3.3

How can I dynamically change the background color of a div based on scroll position in JavaScript?

I’m trying to make a webpage where a div element changes its background color as the user scrolls down the page. I want the color to transition smoothly between different shades as the scroll progresses. I’ve tried using window.onscroll, but I’m struggling to get the right values to make the color change look smooth. Could anyone show me how to achieve this effect using vanilla JavaScript? Thanks in advance!

I attempted using window.onscroll to detect the scroll position and then change the backgroundColor of the div. I tried calculating a color value based on window.scrollY but found the colors were changing too abruptly. Here’s a snippet of what I’ve got so far:

window.onscroll = () => {
const scrollPos = window.scrollY;
const colorValue = Math.min(255, scrollPos / 5); // Attempt to scale color with scroll
document.getElementById(‘myDiv’).style.backgroundColor = rgb(${colorValue}, 100, 150);
};

What I Expected:
“I was hoping for a smooth transition where the background color would gradually change as I scroll down the page. Right now, it’s either changing too quickly or jumping to values I didn’t intend. I’m also open to using different color transitions if there’s a better approach to achieve a fluid, natural effect.”

requests on django api by javascript with CORS error

I have a web application for many years that uses Django and Django Rest Framework. The API is used by a python application and it works correctly:

import requests
response = requests.options(http://example.com/api/albums/)
200
{'name': 'Album List List', 'description': '', 'renders': ['application/json', 'text/html'], 'parses': ['application/json', 'application/x-www-form-urlencoded', 'multipart/form-data'], 'actions': {'POST': ....

I discovered Svelte and I wanted to work with this API but impossible:

let api_ = "http://example.com/api/albums/"
const getAlbums = async () => {
    var response = await fetch(api, {
        mode: 'cors', method: 'GET', headers: {
            'Content-Type': 'application/json'}});
    var result = await response.json();
    return result.results;
Cross-Origin Request Blocked: The “Same Origin” policy does not allow viewing the remote resource located at http://example.com/api/albums/. Reason: The “Access-Control-Allow-Origin” CORS header is missing. Status Code: 200.

I read that you need to install django-cors-headers. but now I have this error:

Exception in thread django-main-thread:
Traceback (most recent call last):
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/utils.py", line 69, in __getitem__
    return self._engines[alias]
KeyError: 'django'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/backends/django.py", line 174, in get_package_libraries
    module = import_module(entry[1])
File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/rest_framework/templatetags/rest_framework.py", line 12, in <module>
    from rest_framework.renderers import HTMLFormRenderer
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/rest_framework/renderers.py", line 17, in <module>
    from django.http.multipartparser import parse_header
ImportError: cannot import name 'parse_header' from 'django.http.multipartparser' (/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/http/multipartparser.py)

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner
    self.run()
File "/usr/lib/python3.10/threading.py", line 953, in run
Traceback (most recent call last):
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/utils.py", line 69, in __getitem__
    return self._engines[alias]
KeyError: 'django'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/backends/django.py", line 174, in get_package_libraries
    self._target(*self._args, **self._kwargs)
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper
    module = import_module(entry[1])
File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module
    fn(*args, **kwargs)
    return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 134, in inner_run
File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
    self.check(display_num_errors=True)
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/core/management/base.py", line 486, in check
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
    all_issues = checks.run_checks(
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/core/checks/registry.py", line 88, in run_checks
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/rest_framework/templatetags/rest_framework.py", line 12, in <module>
    new_errors = check(app_configs=app_configs, databases=databases)
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/core/checks/templates.py", line 10, in check_templates
    from rest_framework.renderers import HTMLFormRenderer
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/rest_framework/renderers.py", line 17, in <module>
    for engine in engines.all():
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/utils.py", line 94, in all
    from django.http.multipartparser import parse_header
ImportError: cannot import name 'parse_header' from 'django.http.multipartparser' (/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/http/multipartparser.py)
    return [self[alias] for alias in self]

The above exception was the direct cause of the following exception:

File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/utils.py", line 94, in <listcomp>
Traceback (most recent call last):
File "/home/vianney/Documents/django_blog/manage.py", line 22, in <module>
    return [self[alias] for alias in self]
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/utils.py", line 85, in __getitem__
    main()
File "/home/vianney/Documents/django_blog/manage.py", line 18, in main
    engine = engine_cls(params)
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/backends/django.py", line 26, in __init__
    execute_from_command_line(sys.argv)
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line
    options["libraries"] = self.get_templatetag_libraries(libraries)
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/backends/django.py", line 88, in get_templatetag_libraries
    utility.execute()
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/core/management/__init__.py", line 436, in execute
    libraries = get_installed_libraries()
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/backends/django.py", line 162, in get_installed_libraries
    self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/core/management/base.py", line 413, in run_from_argv
    return {
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/backends/django.py", line 162, in <dictcomp>
    self.execute(*args, **cmd_options)
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 75, in execute
    return {
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/backends/django.py", line 151, in get_template_tag_modules
    super().execute(*args, **options)
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/core/management/base.py", line 459, in execute
    for name in get_package_libraries(pkg):
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/backends/django.py", line 176, in get_package_libraries
    output = self.handle(*args, **options)
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 112, in handle
    raise InvalidTemplateLibrary(
django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'rest_framework.templatetags.rest_framework': cannot import name 'parse_header' from 'django.http.multipartparser' (/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/http/multipartparser.py)
    self.run(**options)
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 119, in run
    autoreload.run_with_reloader(self.inner_run, **options)
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/utils/autoreload.py", line 671, in run_with_reloader
    start_django(reloader, main_func, *args, **kwargs)
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/utils/autoreload.py", line 660, in start_django
    reloader.run(django_main_thread)
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/utils/autoreload.py", line 343, in run
    autoreload_started.send(sender=self)
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/dispatch/dispatcher.py", line 189, in send
    response = receiver(signal=self, sender=sender, **named)
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/autoreload.py", line 50, in watch_for_template_changes
    for directory in get_template_directories():
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/autoreload.py", line 16, in get_template_directories
    for backend in engines.all():
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/utils.py", line 94, in all
    return [self[alias] for alias in self]
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/utils.py", line 94, in <listcomp>
    return [self[alias] for alias in self]
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/utils.py", line 85, in __getitem__
    engine = engine_cls(params)
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/backends/django.py", line 26, in __init__
    options["libraries"] = self.get_templatetag_libraries(libraries)
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/backends/django.py", line 88, in get_templatetag_libraries
    libraries = get_installed_libraries()
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/backends/django.py", line 162, in get_installed_libraries
    return {
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/backends/django.py", line 162, in <dictcomp>
    return {
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/backends/django.py", line 151, in get_template_tag_modules
    for name in get_package_libraries(pkg):
File "/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/template/backends/django.py", line 176, in get_package_libraries
    raise InvalidTemplateLibrary(
django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'rest_framework.templatetags.rest_framework': cannot import name 'parse_header' from 'django.http.multipartparser' (/home/vianney/Documents/.blog/lib/python3.10/site-packages/django/http/multipartparser.py)

my Python version is 3.10.12, Django is 5.1.2 and Rest Framework is 3.12.4 and I installed the Cors Unlocked add-on under firefox.

does anyone have an explanation? why with python I have access to my api and not with javascript?

thank you for your help.

Calling markdownit() for a dynamically loaded div

<!doctype html>
<html>
<head>

<script src="https://cdnjs.cloudflare.com/ajax/libs/markdown-it/13.0.1/markdown-it.min.js" integrity="sha512-SYfDUYPg5xspsG6OOpXU366G8SZsdHOhqk/icdrYJ2E/WKZxPxze7d2HD3AyXpT7U22PZ5y74xRpqZ6A2bJ+kQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>


<script>
window.onload = function() {
  var md = window.markdownit();
  var div = document.getElementsByClassName('markdown');
  for(var i = 0; i < div.length; i++) {
    var content = div[i].innerHTML;
    document.getElementsByClassName('markdown')[i].innerHTML = md.render(content);
  }
}
</script>

</head>
<body>


<div class="markdown">
# h1 Heading
## h2 Heading
### h3 Heading
#### h4 Heading
##### h5 Heading
###### h6 Heading

+ one
+ two
  + two and half
+ three
  + three and half
    + three point seventy five
</div>

</body>
</html>

This is an example of how to call markdownit() for a specific div after the page loads.

On my page, div tags are loaded dynamically after certain user actions. How do I call markdownit() for an emerging div with the id=”markdown” attribute?

Creating a Zoom Effect for Website Navigation

I’m looking to implement a zoom effect for my website similar to the one found at (50 Jahre Hitparade) . Instead of a traditional scrolling experience, I want each new section to come into view with a dynamic zoom effect.

Does anyone have tips or resources for achieving this effect?

I expected to see a clean transition where each section smoothly zooms in as the user navigates, providing an engaging experience without the need for traditional scrolling.

when i try get value cell current selection row give me previous value of cell

i created InterActive Datagrid and it’s colum currencyId create dynamicAction event execute java script query and set this code

// Get the Interactive Grid model
var model = apex.region("PAYEMNTDetails").widget().interactiveGrid("getViews", "grid").model;

// Retrieve the selected rows
var selectedRecords = model.getSelectedRecords();

if (selectedRecords && selectedRecords.length > 0) {
    // Access the first selected record
    var record = selectedRecords[0];
    
    // Get the CurrencyId field value
    var currencyId = record[3]; // Replace 3 with the actual index of CurrencyId field, or:
    // var currencyId = record.getValue("CURRENCYID"); // If the field name is "CURRENCYID"
    
    console.log("CurrencyId:", currencyId);
} else {
    console.log("No row is selected.");
}

i want to get the current value after changed

the problem : this code give me previous value before change

constructor of javascript Date for string [duplicate]

I have string like this, 2024-11-03T03:08:39.209797+09:00

Which is passed from python as json format.

Now I try to do this

var myDate = date("2024-11-03T03:08:39.209797+09:00")

However, it doesn’t work correctly.

I think for javascript it should be like this,

#parsing string here

var myDate = date(2024,11,03,3,8,39)

However it looks like a bit ackward.

Is there any better method?

How to add automatic page numeration in Google App Scripts html when a table spans over several pages

I have an html in Google App Scripts that contains a table that might span over several pages, and I want to add something like “Page 3/4” at the bottom right of each page.

In my App Script I create a template from the html like this:
const template = HtmlService.createTemplateFromFile('my-html-file-name');

and then I get the pdf like this:

const htmlOutput = template.evaluate().getContent();
const pdfBlob = Utilities.newBlob(htmlOutput, 'text/html').getAs('application/pdf');
pdfBlob.setName(`file-name.pdf`);
const pdfBytes = pdfBlob.getBytes();
const pdfBase64 = Utilities.base64Encode(pdfBytes);

Note that the page numeration should indicate the current page and the total number of pages “Page 1/4”.

I’ve tried setting the styles on the html like this:

    @page {
      size: A4;
      margin: 0;
    }

    .page-footer {
      position: fixed;
      bottom: 0;
      right: 0;
      margin: 10px;
      font-size: 10px;
    }

    .page-footer::after {
      counter-increment: page;
      content: counter(page);
    }
    
    .....

    <div class="page-footer"></div> </body>

and I’ve also tried this approach using a script:

<script>
    document.addEventListener('DOMContentLoaded', function() {
      const totalPages = Math.ceil(document.body.scrollHeight / window.innerHeight);
      const pageNumbers = document.querySelectorAll('.page-footer');
      pageNumbers.forEach((pageNumber, index) => {
        pageNumber.textContent = `${index + 1}/${totalPages + 1}`;
      });
    });
</script>

Note here that the totalPages get calculated correctly but there is only one element in the pageNumbers array, since there is only one div with that class, but yet it is shown in all the pages due to the “fixed” position.

Managing checkbox states in a JavaScript array without impacting other checkboxes

I have multiple checkboxes, and each checkbox is assigned either value=”0″ or value=”1″. I want to check each checkbox; if a checkbox has value=”0″, the text color of that checkbox should change to red. I have written the following code:

const allCheckboxes = document.querySelectorAll('input[type="checkbox"]');
for (let k = 0; k < allCheckboxes.length; k++) {
    const checkbox = allCheckboxes[k];
    if (checkbox.value === "0") {  
        checkbox.parentNode.style.color = "red";  
    }
}

When I run the function, all the checkboxes have their text color changed to red. Even if I change "0" to "1", the result does not change.
Please tell me the reason and how to fix it.
This is CSS

.correct-answer {
      color: red;
    }

This is HTML

<p><b>Question 1:</b> A ball is dropped from a height of 5.00 m and completely elastically collides with the ground (the rebound speed from the ground is equal to the speed just before hitting the ground). Assume that mechanical energy is not lost due to air resistance. Take $g = 10 text{m/s}^2$.</p>
<div id="trueFalseForm">
  <input type="checkbox" name="q19" value="0"> <b>a)</b> The motion of the ball is simple harmonic motion.<br>
  <input type="checkbox" name="q19" value="1"> <b>b)</b> The speed of the ball when it hits the ground is $10 text{m/s}$.<br>
  <input type="checkbox" name="q19" value="1"> <b>c)</b> The motion of the ball is periodic.<br>
  <input type="checkbox" name="q19" value="0"> <b>d)</b> The period of the ball's motion is $1 text{s}$.<br>
</div>
<p><b>Question 2:</b> An object oscillates harmonically; it takes 0.25 seconds to move from a point with zero velocity to the next point with zero velocity. The distance between these two points is 36 cm. Calculate (a) the period, (b) the frequency, and (c) the amplitude of the motion.</p>
<div id="trueFalseForm">
  <input type="checkbox" name="q20" value="1"> <b>a)</b> The period of the oscillation is 0.5 s.<br>
  <input type="checkbox" name="q20" value="0"> <b>b)</b> The amplitude of the oscillation is 36 cm.<br>
  <input type="checkbox" name="q20" value="1"> <b>c)</b> The maximum speed of the object is 226.19 cm/s.<br>
  <input type="checkbox" name="q20" value="0"> <b>d)</b> The maximum distance the object can travel in 0.125 s is 18 cm.<br>
</div>

How to create a proxy function for function call chaining in javascript?

For example, I would like to be able to execute a(b)(c) where a, b, and c are proxy functions that I create.

So far I wrote the following piece of code:

  function createProxy(funcName) {
    const proxy = new Proxy(function () {}, {
      apply(target, thisArg, args) {
        result += `${funcName} `;

        // Process and log each argument's name if it has a mapped proxy
        args.forEach((arg) => {
          if (proxiesMap.has(arg)) {
            const argName = proxiesMap.get(arg);
            result += `${argName} `;
          }
        });

        // Return the proxy for chaining if no arguments, or pass through argument proxy if it exists
        return args.length > 0 ? args[0] : proxy;
      }
    });

    // Store the mapping from proxy to name
    proxiesMap.set(proxy, funcName);
    proxiedValues.add(funcName);
    return proxy;
}

This is not really what I want, because if we have multiple statements that are executed on different lines, this will output:

a(b)(c);
d(e);

The above is outputting a b b c c d d e (due to appending the middle calls twice because on one hand they are function names on another hand they are arguments). The above should result in:

a b c
d e

I had another idea but it led to the same result:

  function createProxy(param) {
    let isFirstCall = true;
    const proxy = function(...args) {
      if (isFirstCall) {
        result += `${param} `;
        isFirstCall = false;
      }

      // Invoke any function arguments
      args.forEach(arg => {
        if (typeof arg === 'function') {
          arg();
        }
      });

      // Return the same function for chaining
      return placeholder;
    };
    // Wrap with proxy
    return new Proxy(placeholder, {
      apply(target, thisArg, args) {
        return target(...args);
      }
    });
  }

Where am I going wrong in function chaining proxieS?

How to automate the ChatGPT website with new security updates?

enter image description here

ChatGPT used to be fairly easy to automate via an extension on the page (which is allowed according to what an openai customer rep told me via chat), you used to just call the backend API/conversation end point, as you can see above, with the same payload that it’s being shown initially with a body describing the new message ID and parent message ID etc., and it worked. Several extensions on the chrome store did this.

Now they have a few extra steps, significantly:

fetch("https://chatgpt.com/backend-api/sentinel/chat-requirements", {
  "headers": {
    "accept": "*/*",
    "accept-language": "en-US,en;q=0.9",
    "authorization": "Bearer <removed for 
  .",
    "content-type": "application/json",
    "oai-device-id": "<removed for security>",
    "oai-language": "en-US",
    "sec-ch-ua": ""Not-A.Brand";v="99", "Chromium";v="124"",
    
  },
  "referrer": "https://chatgpt.com/c/<removed for security>",
  "referrerPolicy": "strict-origin-when-cross-origin",
  "body": "{"p: <removed for security>"}",
  "method": "POST",
  
});

Which submits as the body the parameter “p” which appears to be some kind of key that must have been gotten or derived somehow from a previous request, but I’m not sure what.

Which then returns an object with a list of a few different kinds of keys (too big to copy here), which appear to somehow be used in this next request:

enter image description here

enter image description here

enter image description here

There’s several keys that are included as new headers which appear to be partially based on the earlier payload.

The problem is that I’m struggling to figure how how those tokens are derived from the earlier payload. It’s somewhere in the minimized code on the page but it’s too complicated to navigate and figure out on my own. Plus I think there are several other requests that it’s getting information from but it’s too hard to figure out exactly what is done to get those token values.

When I try making the request to conversation with new message IDs etc like I used to, even when copying in some new token values, I always get the error “unusual activity detected…”

Has anyone figured out how to do this with the updated security?