How to sort 2D array from horizontal (left-to-right) to vertical (top-to-bottom)

I want to convert the 2d array which is missing some values and has been sorted from left to right to a new array which is sorted from top to bottom like below examples. Cols and rows and the number of items in the array are dynamic, can be changed to any number. Thank you!

  1. When cols = 3, rows = 3
    Input:
0 | 1 | 2
3 | 4 | 5
6

Expected:

0 | 3 | 5
1 | 4 | 6
2 | 
  1. When cols = 5, rows = 2

Input:

0 | 1 | 2 | 3 | 4
5 | 6

Expected:

0 | 2 | 4 | 5 | 6
1 | 3

How to reset and prevent localStorage data from persisting in JavaScript on page reload?

I’m working on a JavaScript application where I manage a table of products. Each product row can be dynamically updated, and I store the updates in localStorage (both the original product list and any newly added products). However, I am encountering an issue where the addedProducts data persists in localStorage even after I explicitly reset it on page load.

Problem:
On page load, I am trying to reset the addedProducts array to an empty state. This is working as long as I stay on the same page.
However, if I navigate away and return to the page, the data from localStorage gets re-populated in the addedProducts array after the page completes loading, despite attempting to clear it.
I am unsure why the data persists and why it continues to populate even after I’ve explicitly
reset addedProducts.

What I’ve tried:
I tried resetting addedProducts to an empty array upon page load, but it still retrieves old data from localStorage once the page completes loading. (Again, as long as I remain on the same page there is no problem. If I naviaget away and return to the page, the data in addedProducts is pre populated.)
I also tried clearing localStorage during the beforeunload event, but the problem still occurs on page reload. Stuck.

My code:

<script>
document.addEventListener('DOMContentLoaded', function () {
    // Fetch previously saved original products from localStorage (if any)
    let originalProducts = JSON.parse(localStorage.getItem('originalProducts')) || [];
    let lastSavedRowIndex = originalProducts.length > 0 ? parseInt(originalProducts[originalProducts.length - 1].rowIndex) : -1;

    // Ensure addedProducts is always reset and never fetched from localStorage
    let addedProducts = [];  // Explicitly reset addedProducts to an empty array

    // Function to save original products to localStorage
    function saveOriginalProducts() {
        const productRows = document.querySelectorAll('#pos_table tbody tr');
        const products = [];

        productRows.forEach(row => {
            const rowIndex = row.getAttribute('data-row_index');

            // Extract product details
            const productNameElement = row.querySelector('.text-link');
            const productName = productNameElement ? productNameElement.textContent.replace(/s+/g, ' ').trim() : '';
            const productQtyElement = row.querySelector('.input_quantity');
            const productQty = productQtyElement ? productQtyElement.value.trim() : '';
            const productPriceElement = row.querySelector('.pos_unit_price_inc_tax');
            const productPrice = productPriceElement ? productPriceElement.value.trim() : '';
            const productSubtotalElement = row.querySelector('.pos_line_total');
            const productSubtotal = productSubtotalElement ? productSubtotalElement.value.trim() : '';

            // Push only valid rows
            if (rowIndex && productName && productQty && productPrice && productSubtotal) {
                products.push({
                    rowIndex: rowIndex,
                    name: productName,
                    qty: productQty,
                    price: productPrice,
                    subtotal: productSubtotal
                });
            }
        });

        if (products.length > 0) {
            localStorage.setItem('originalProducts', JSON.stringify(products));
            console.log("Original products successfully saved to localStorage:", products);
        }
    }

    // Function to save added products to localStorage
    function saveAddedProducts() {
        const productRows = document.querySelectorAll('#pos_table tbody tr');
        const newAddedProducts = [];

        productRows.forEach(row => {
            const rowIndex = row.getAttribute('data-row_index');

            // Extract product details
            const productNameElement = row.querySelector('.text-link');
            const productName = productNameElement ? productNameElement.textContent.replace(/s+/g, ' ').trim() : '';
            const productQtyElement = row.querySelector('.input_quantity');
            const productQty = productQtyElement ? productQtyElement.value.trim() : '';
            const productPriceElement = row.querySelector('.pos_unit_price_inc_tax');
            const productPrice = productPriceElement ? productPriceElement.value.trim() : '';
            const productSubtotalElement = row.querySelector('.pos_line_total');
            const productSubtotal = productSubtotalElement ? productSubtotalElement.value.trim() : '';

            // Check if the product is new (rowIndex is greater than lastSavedRowIndex)
            if (parseInt(rowIndex) > lastSavedRowIndex) {
                newAddedProducts.push({
                    rowIndex: rowIndex,
                    name: productName,
                    qty: productQty,
                    price: productPrice,
                    subtotal: productSubtotal
                });
            }
        });

        // Remove duplicates from addedProducts if they exist in originalProducts
        newAddedProducts.forEach(newProduct => {
            // Remove any existing product with the same rowIndex in addedProducts
            addedProducts = addedProducts.filter(existingProduct => existingProduct.rowIndex !== newProduct.rowIndex);

            // Now add the new product to addedProducts
            addedProducts.push(newProduct);
        });

        // Log the updated addedProducts BEFORE saving it to localStorage
        console.log("Updated addedProducts:", addedProducts);

        // Now save to localStorage
        localStorage.setItem('addedProducts', JSON.stringify(addedProducts));

        // Update the last saved rowIndex
        lastSavedRowIndex = Math.max(...newAddedProducts.map(p => parseInt(p.rowIndex)), lastSavedRowIndex);
    }

    // Function to handle input changes (including quantity, price, and subtotal)
    function handleInputChange(event) {
        const row = event.target.closest('tr');
        const rowIndex = row.getAttribute('data-row_index');

        // Extract updated product details directly from the row
        const productNameElement = row.querySelector('.text-link');
        const productName = productNameElement ? productNameElement.textContent.replace(/s+/g, ' ').trim() : '';
        const productQtyElement = row.querySelector('.input_quantity');
        let productQty = productQtyElement ? productQtyElement.value.trim() : '';
        productQty = productQty.replace(/[^0-9.]/g, ''); // Sanitize quantity to only allow numbers

        const productPriceElement = row.querySelector('.pos_unit_price_inc_tax');
        const productPrice = productPriceElement ? productPriceElement.value.trim() : '';
        const productSubtotalElement = row.querySelector('.pos_line_total');
        const productSubtotal = productSubtotalElement ? productSubtotalElement.value.trim() : '';

        // Validate the productQty
        if (!productQty || isNaN(productQty) || parseFloat(productQty) <= 0) {
            productQty = '1'; // Default to 1 if the value is invalid
        }

        // Recalculate the subtotal (if applicable)
        const calculatedSubtotal = (parseFloat(productQty) * parseFloat(productPrice)).toFixed(2);
        if (productSubtotal !== calculatedSubtotal) {
            row.querySelector('.pos_line_total').value = calculatedSubtotal;
        }

        // Update the addedProduct array
        const updatedProduct = {
            rowIndex: rowIndex,
            name: productName,
            qty: productQty,
            price: productPrice,
            subtotal: calculatedSubtotal
        };

        // Check if the row belongs to originalProducts
        const originalIndex = originalProducts.findIndex(p => p.rowIndex === rowIndex);
        if (originalIndex !== -1) {
            // If the product exists in originalProducts, remove it from addedProducts
            const addedIndex = addedProducts.findIndex(p => p.rowIndex === rowIndex);
            if (addedIndex !== -1) {
                addedProducts.splice(addedIndex, 1); // Remove the product from addedProducts
            }
        } else {
            // Update existing product in addedProducts
            const addedIndex = addedProducts.findIndex(p => p.rowIndex === rowIndex);
            if (addedIndex !== -1) {
                addedProducts[addedIndex] = updatedProduct;
            } else {
                // Add as a new product if not found in either list
                addedProducts.push(updatedProduct);
            }
        }

        // Update localStorage
        localStorage.setItem('originalProducts', JSON.stringify(originalProducts));
        localStorage.setItem('addedProducts', JSON.stringify(addedProducts));
        console.log("Updated originalProducts:", originalProducts);
        console.log("Updated addedProducts:", addedProducts);
    }

    // Attach event listeners for product changes
    function addEventListenersToTable() {
        const productRows = document.querySelectorAll('#pos_table tbody tr');
        productRows.forEach(row => {
            const qtyInput = row.querySelector('.input_quantity');
            const priceInput = row.querySelector('.pos_unit_price_inc_tax');
            
            // Add event listeners to the input fields
            if (qtyInput) {
                qtyInput.addEventListener('input', handleInputChange);
            }

            if (priceInput) {
                priceInput.addEventListener('input', handleInputChange);
            }
        });
    }

    // Initialize table and event listeners
    const posTable = document.querySelector('#pos_table tbody');
    if (posTable) {
        saveOriginalProducts();
        addEventListenersToTable();
    } else {
        console.warn("POS table not found on the page.");
    }

    // Detect changes in the product table
    if (posTable) {
        const observer = new MutationObserver(() => {
            saveAddedProducts(); // Save newly added products
            addEventListenersToTable(); // Reattach listeners
        });

        observer.observe(posTable, {
            childList: true,
            subtree: true
        });
    }

    // Clear localStorage on page unload
    window.addEventListener('beforeunload', function () {
        localStorage.removeItem("addedProducts");  // Clear added products on page exit
        console.log("Clearing addedProducts from localStorage before leaving the page.");
    });
});
</script>

Can’t figure out a way to stringify a MutationRecord

Goal: I am trying to figure out a way to store MutationRecords (ideally serialize them in some way and store them in a database) to later be able to replay them.

When my page loads, a snapshot of the DOM is taken in the form of a string and can later be reproduced in an iframe. But I also want to be able to replay any DOM changes (e.g. dynamically added form fields or other content) that occur while the page was being used.

I am using the MutationObserver API like so:

const handleDomChange = (mutationList, observer) => {
    console.log("Original:", mutationList);
}

const targetNode = document.body;
const config = {
    attributes: true,
    childList: true,
    subtree: true
};
const observer = new MutationObserver(handleDomChange);
observer.observe(targetNode, config);

When some dynamic content is added, I get an array of MutationRecords, in my case there is only one element there:

enter image description here

At this point I want to JSON.stringify that array and upload it to my DB. Of course, I can’t do that.

The issue really boils down to turning DOM nodes in addedNodes and target into plain JS objects. For which I use the toJSON function borrowed here: https://github.com/sumn2u/dom-to-json/blob/master/lib/index.js

But it apparently isn’t doing an adequate job as I cannot later use that object to replay the mutation.

Incidentally, here is the code I use to replay (or redo) mutations: https://gist.github.com/anonyco/f5f88c3845f50935d4ea0187e3749878

so I am a little stumped as to how to accomplish this.

Reactjs Chrome extension: how to open react component in new tab, react scripts

I’m trying to create a simple Chrome extension: when it’s clicked, a small popup is opened that has an Expand button (Popup.js). When an Expand button is clicked, a new tab is opened (Window.js).

However, I can’t get it to work.

App.js:

import React from "react";
import Popup from "./Popup";

const App = () => {
  return (
      <div>
        <h1>React Chrome Extension</h1>
        <Popup />
      </div>
  );
};

export default App;

Popup.js

/*global chrome*/
import React from "react";

const Popup = () => {
    const handleExpandClick = () => {
        chrome.tabs.create({
            url: chrome.runtime.getURL("window.html")
        });
    };

    return (
        <div style={{ width: "200px", height: "100px", padding: "20px" }}>
            <button onClick={handleExpandClick}>EXPAND</button>
        </div>
    );
};

export default Popup;

Window.js

/*global chrome*/
import React from "react";

const Window = () => {
    return (
        <div>
            <h1>This is the new window opened by the extension!</h1>
        </div>
    );
};

export default Window;

background.js:

chrome.runtime.onInstalled.addListener(() => {
    console.log("Extension installed!");
});

package.json:

{
  "name": "react-chrome-extension",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "cra-template": "1.2.0",
    "react": "^19.0.0",
    "react-dom": "^19.0.0",
    "react-scripts": "5.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

manifest.json:

{
  "manifest_version": 3,
  "name": "React Chrome Extension",
  "version": "1.0",
  "description": "A simple React-based Chrome extension",
  "permissions": ["tabs"],
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_popup": "popup.html"
  },
  "host_permissions": [
    "http://*/*",
    "https://*/*"
  ],
  "icons": {
    "16": "favicon.ico",
    "48": "favicon.ico",
    "128": "favicon.ico"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["background.js"]
    }
  ]
}

Directory structure:

enter image description here

The contents of build folder have been copied into public folder:

enter image description here

When I load the extension inside Chrome:

the extension appears on extension bar, but when I click it:

enter image description here

Instead of a popup I get an empty window.

The popup.html and window.html generated during build seem to have empty body:

popup.html:

<!-- public/popup.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Popup</title>
</head>
<body>
<div id="root"></div>
<script src="popup.js"></script>
</body>
</html>

window.html:

<!-- public/window.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Window</title>
</head>
<body>
<div id="root"></div>
<script src="window.js"></script>
</body>
</html>

And there are no window.js or popup.js anywhere in the build folder or its subfolders.

Why am I getting the error (CSRF token from the ‘X-Csrftoken’ HTTP header has incorrect length.)?

I’m trying to send from React a PUT request to my Django server for updating a Django model field. Here’s the code

const handleStatusChange = async (projectId, newStatus) => {
        try {
            const response = await fetch(`/api/project/${projectId}/status`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
                },
                body: JSON.stringify({ status: newStatus })
            });

            if (response.ok) {
                setProjects(prevProjects => 
                    prevProjects.map(project => 
                        project.id === projectId ? { ...project, status: newStatus } : project
                    )
                );
                setStatusDropdown(null); 
                setUpdatingProjectId(null); 
            } else {
                console.error('Failed to update project status');
            }
        } catch (error) {
            console.error('Error updating project status:', error);
        }
    };

The problem is that the console logs the message ‘Failed to update project status’ because of the server error: Forbidden (CSRF token from the ‘X-Csrftoken’ HTTP header has incorrect length.): /api/project/1/status
WARNING:django.security.csrf:Forbidden (CSRF token from the ‘X-Csrftoken’ HTTP header has incorrect length.): /api/project/1/status
[06/Dec/2024 17:37:21] “PUT /api/project/1/status HTTP/1.1” 403 2549. I have no clue of what’s leading to the error. I applied the same logic to another PUT request in other page and I didn’t have the issue. Can somebody explain please how I can manage the csrf token length? I’m not “manually” generating such token.

I’ll share the complete console error if helps:

index.js:25 Failed to update project status
handleStatusChange  @   index.js:25
await in handleStatusChange     
onClick @   index.js:61
callCallback    @   react-dom.development.js:3942
invokeGuardedCallbackDev    @   react-dom.development.js:3991
invokeGuardedCallback   @   react-dom.development.js:4053
invokeGuardedCallbackAndCatchFirstError @   react-dom.development.js:4067
executeDispatch @   react-dom.development.js:8273
processDispatchQueueItemsInOrder    @   react-dom.development.js:8305
processDispatchQueue    @   react-dom.development.js:8318
dispatchEventsForPlugins    @   react-dom.development.js:8329
(anónimo)   @   react-dom.development.js:8538
batchedEventUpdates$1   @   react-dom.development.js:22426
batchedEventUpdates @   react-dom.development.js:3742
dispatchEventForPluginEventSystem   @   react-dom.development.js:8537
attemptToDispatchEvent  @   react-dom.development.js:6035
dispatchEvent   @   react-dom.development.js:5954
unstable_runWithPriority    @   react.development.js:2764
runWithPriority$1   @   react-dom.development.js:11306
discreteUpdates$1   @   react-dom.development.js:22443
discreteUpdates @   react-dom.development.js:3753
dispatchDiscreteEvent   @   react-dom.development.js:5919

Set Mapbox layer text-size based on multiple properties

I have a layer of points on my map. I want all points whose id belong to a list to be size 16 at all times. I want the remaining points to change their size based on the zoom level of the map. Each of these conditions can be accomplished separately, but I am unable to combine them.

Here is the closest I got:

this.map.setLayoutProperty('layer', 'text-size', [
    'match',
    ['get', 'id'], idsToShow, 16,
    ['interpolate', ['linear'], ['zoom'], 6, 6, 8, 16]
]);

When I try to run this I get the following error:

layers.layer.layout.text-size: "zoom" expression may only be
used as input to a top-level "step" or "interpolate" expression,
or in the properties of atmosphere.

This suggests to me that Mapbox isn’t capable of using a zoom expression has a fallback. Is there a way to achieve this without splitting the data into two layers?

Issue with npm install (node.exe) popups in VSCode, but not in admin mode

I have an issue where, on every startup of VSCode, or every file opening, I get popups from node.exe related to npm install. The multiple quick popups are annoying and only appear when I open VSCode in non-admin mode. When I run VSCode as administrator, the issue doesn’t happen.

I tried uninstalling Node.js globally and reinstalling it again, but it didn’t help.

What could be causing these popups to appear, and how can I prevent them from showing up every time I launch VSCode in non-admin mode?

enter image description here

My Google Meet Addon presented in Google Meet won’t follow the specified sidePanelUrl (or sidePanelUri)

I have written a Google Meet Addon in Vue 3/Typescript and serve the static page it from a public available and secure website. The URL of that website I have specified in the manifest.json in my Google Cloud project.
I also specified a logoURL in there and that is accessed and shown without a problem.

I tested the URL in my Chrome browser and it showed my page (ofcource telling me that it couldn’t find the corresponding meeting).

Can anyone tell me why it does not access my Webserver?

My deployment.json:

   {
       "oauthScopes": ["https ://www.googleapis.com/auth/meet.addons.execute"],
       "addOns": {
             "common": {
                 "name": "My Meet addon v1.0.1",
                 "logoUrl": "https://home.xxx.nl:8000/favicon.ico"
             },
             "meet": {
                 "web": {
                      "sidePanelUri": "https://home.xxx.nl:8000/static/index.html",
                      "addOnOrigins": ["https://home.xxx.nl:8000"],
                      "sidePanelUrl": "https://home.xxx.nl:8000/static/index.html",
                      "darkModeLogoUrl": "https://home.xxx.nl:8000/favicon.ico"
                 }
             }
         }
     }

`
I expected to see in my webserver the GET HTTP requests from Google Meet.

Unable to reference NPM package globally

webpack.config.js

const path = require('path');
const webpack = require('webpack');

module.exports = {
  entry: '/src/index.js',

  output: {
    path: path.resolve(__dirname, '..','..', 'public_html', 'dist', 'webpack'),

    filename: 'dist.js',
  },
  
  plugins: [
     new webpack.ProvidePlugin({
       cheerio: 'cheerio',
     }),
   ],

  module: {
    rules: [
      {
        test: /.js$/, 
        exclude: /node_modules/,
      },
    ],
  },

  devtool: 'source-map',
};

index.js

var _ = require('lodash');
var cheerio = require('cheerio');

test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test Lodash</title>
    <script src="/dist/webpack/dist.js"></script>
    <script defer type="text/javascript">
        window.onload = function() {
            const shuffled = _.shuffle([1, 2, 3, 4, 5]);
            console.log('Shuffled array:', [1, 2, 3, 4, 5]);
            document.getElementById("parentID").innerHTML+= "shuffled array: " + shuffled + '<br>';

            const $ = cheerio.load('<ul id="fruits">...</ul>');
            $.html();
        };
    </script>
</head>
<body>
    <div id="parentID"><br></div>
</body>
</html>

error: Uncaught ReferenceError: cheerio is not defined

I am implementing npm and webpack and currently need to reference is from html pages like test.html. I am just looking to bundle and reference packages from npm in this way.

The lodash portion of this works properly. I also tried jquery but got the same error related to the $ character

home
|--> public_html
|-----> test.hml
|-----> dist
|-------> webpack
|---------> dist.js
|--> san_mounted
|-----> npm
|--------> src
|-----------> index.js
|--------> webpack.config.js
|--------> package-lock.json
|--------> package.json
|--------> node-modules

How to pass state data with React?

I am writing a simple web app in React.

I’m trying to send data from one page to another using the useLocation hook in React Router, and I can’t seem to pass the data. For some reason, despite the value of un changing, as shown by console logs, when I pass un as a state to "/link-page", the value is passed as if no changes have been made. That is, the username displayed on the link page is simply 'h'.

Here is my code:

Home.jsx:

import { Link } from "react-router-dom";

let un = 'h'

function handleChange() {
    un = document.getElementById("username").value;
}

function Home() {
    return (
        <>
            <h1>welcome to duel.fm!</h1>
            <h3>enter your last.fm username below</h3>
            <form>
                <input type={"text"} id={"username"} onChange={handleChange} />
                <Link to={"/link-page"} state={{ username: un }}>
                    <input type={"submit"} value={"submit"} />
                </Link>
            </form>
        </>
    )
}

export default Home;

LinkPage.jsx:

import { useLocation } from 'react-router-dom';

function LinkPage() {
    const location = useLocation();
    const username = location.state.username;

    return (
        <>
            <h3>share this link with your friend!</h3>
            <h5>{username}</h5>
        </>
    )
}

export default LinkPage;

Pointermove events stop when element moved in DOM

If you drag the green square over one of the other squares it inserts it before (moves it), but if you continue to drag without letting go of your mouse button, this action doesn’t continue to work for the remaining squares. The onpointermove event only fires when over the green button itself, not the rest of the DOM at this point.

I presume this is something to do with the fact it’s moved in the DOM, any ideas how to work around this? I have to use the Pointer Capture API to perform this action.

const divs = Array.from(document.querySelectorAll("div"));

divs.forEach((div) => {
  function beginSliding(e) {
    div.onpointermove = slide;
    div.setPointerCapture(e.pointerId);
  }

  function stopSliding(e) {
    div.onpointermove = null;
    div.releasePointerCapture(e.pointerId);
  }

  function slide(e) {
    const ele = document.elementFromPoint(e.clientX, e.clientY);
    
    console.log("move");
    
    if (ele === e.target || !divs.includes(ele)) {
        return;
    }
    
    div.parentElement.insertBefore(div, ele)
  }

  div.onpointerdown = beginSliding;
  div.onpointerup = stopSliding;
});
nav {
  display: flex;
  gap: 10px;
}

div {
  height: 30px;
  width: 100px;
  user-select: none;
}

#a { background: grey; }
#b { background: red; }
#c { background: blue; }
#d { background: yellow; }
#e { background: green; }
<nav>
  <div id="a"></div>
  <div id="b"></div>
  <div id="c"></div>
  <div id="d"></div>
  <div id="e"></div>
</nav>

JSFiddle https://jsfiddle.net/u7f2taLj/2/

Make clickable row in React Data Table call component that redirects to new page in NextJS

I’m using NextJS 15.0. I have a React Data Table Component (version 7.6.2) and I’ve made the rows clickable. When a user clicks a row, it calls a function called onHandleClick. Here is the code…

<DataTable
  onRowClicked={onHandleClick}
/>

Here is what the onHandleClick function looks like…

const onHandleClick = (row:any) => {
  const router = useRouter();
  router.push("/");
}

I want two things to happen:

FIRST, I want to redirect the user (after they click the row) to a new page or I want a new component to load…

and

SECOND, I want the data (the parameter row in the onHandleClick function) to pass over to the new page/component so that I can populate the page/component with that data to be displayed to the user.

I tried the code above and I’m getting an Invalid Hook Call error in the browser. It’s not redirecting me when I click on any row in the Data table.

Here’s what I did to try to fix this issue:

I tried using UseEffect() inside the function call.

I tried using onClick as a parameter inside the component.

These efforts did not fix the issue. Does anyone have any suggestions?

Thanks in advance!

Chart.js register functions not recognizing any extensions (chartjs-chart-geo and chartjs-chart-wordcloud)

I’m working on a dashboard for a web application. The application uses Flask, and the dashboard is built with the Chart.js framework. For some charts, such as a word cloud and a Choropleth to display an interactive map, I’m using Chart.js extensions, specifically chartjs-chart-wordcloud and chartjs-chart-geo, respectively. The plotting of these charts was working fine until, without any noticeable changes on my part, I started receiving the error: “Uncaught Error: ‘wordCloud’ is not a registered controller.” and a similar error for the Choropleth chart. I am registering both controllers from these extensions.

I’ve tried other ways of importing, but I haven’t had any success.
This is my code:

import {Chart, registerables} from 'https://esm.sh/[email protected]';
import {WordCloudController, WordElement} from 'https://esm.sh/[email protected]';
import {
    topojson,
    ChoroplethController,
    GeoFeature,
    ProjectionScale,
    ColorScale,
    } from 'https://esm.sh/[email protected]';


Chart.register(WordCloudController, WordElement, ChoroplethController, GeoFeature, ProjectionScale, ColorScale, ...registerables)

// [...]

function insert_cloud_word_chart(element, infos) {
    const config = {
        type: WordCloudController.id,
        data: {
            labels: infos['labels'],
            datasets: [
                {
                    label: 'Frequência',
                    data: infos['data'],
                },
            ],
        },
        options: {
            responsive: false,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                },
            },
            elements: {
                word: {
                    fontFamily: 'sans-serif',
                    color: (ctx) => {
                        // Define uma cor para cada palavra com base no índice
                        const colors = ['#003D6A', '#22CBE4', '#2662F0', '#333333'];
                        return colors[ctx.index % colors.length];
                    },

                }
            }
        },
    }

    new Chart(element, config)
}

I also used the console.log(Chart.registry.controllers) function to check if Chart.js was correctly registering the controllers. The result showed that even though I called the function and the controllers were imported correctly, they are not being registered.

block cheating using tamper monkey and ant-captcha api

i have a game built with php , it is about wars and stuff .

we have set captcha and other protection methods like tracking click position and other security method in order to block any attempt of cheating , but then someone sent us a viedo laughing at us that he managed to build a bot using tamper monkey and linked anti-captcha.com api to solve our captcha for him automatically..

i tried to do csp policy and intercept the connection but noting was able to stop the bot ( I tried it myself for testing at my local )

what I understood is that is has to convert the img into base64 before sending it to anti-captcha api , I tried block that as well but also not successful .

what did work somehow is putting trusted-types ‘none’ , but when do that a lot of the game functionality stop being working as it depends on innerHTml and other services as well that is being used to track and analytics ( and I am afraid it will affect cloudflare as well ) .

any solutions ?

note : please do not say “let them ” , this affect the game and players so much

403 error with CSRF when accesing Django login by axios

  await axios.get("http://localhost:8000/get_csrf_token/").then((res)=>{
    console.log(res.data.csrf_token);
    axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
    axios.defaults.xsrfCookieName = "csrftoken";
    axios.defaults.withCredentials = true;
    axios.post('http://localhost:8000/login/',{
      username:'admin',
      password:'Kv79NExi'
      
    }, {
      headers: {
      'Content-Type': 'application/json',
      'X-CSRFToken': res.data.csrf_token,
      }
    })
    .then((response) => {
      log("response login",response.data);
    });
  });

I am trying to access django login from command line script(jest) not browser, however it shows the error like this,

<p>Reason given for failure:</p>n' +
  '    <pre>n' +
  '    CSRF cookie not set.n' +
  '    </pre>n' +

It returns 403 error, it looks like sending csrf_token correctly.

Where am I wrong?

Ran all test suites matching /TopPage/i.

node:internal/process/promises:288
            triggerUncaughtException(err, true /* fromPromise */);
            ^
AxiosError {
  message: 'Request failed with status code 403',
  name: 'AxiosError',
  code: 'ERR_BAD_REQUEST',
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [ 'xhr', 'http', 'fetch' ],
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    xsrfCookieName: 'csrftoken',
    xsrfHeaderName: 'X-CSRFTOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    env: {
      FormData: [Function: FormData] {
        LINE_BREAK: 'rn',
        DEFAULT_CONTENT_TYPE: 'application/octet-stream'
      },
      Blob: [class Blob]
    },
    validateStatus: [Function: validateStatus],
    headers: Object [AxiosHeaders] {
      Accept: 'application/json, text/plain, */*',
      'Content-Type': 'application/json',
      'X-CSRFToken': '9aSiDra8P3LzU0hMlSFZ9yqX5fllDySQljBRyHM6jjSYfuZ1BWrCUF9blkElzl1v',
      'User-Agent': 'axios/1.7.9',
      'Content-Length': '42',
      'Accept-Encoding': 'gzip, compress, deflate, br'
    },
    withCredentials: true,
    method: 'post',
    url: 'http://localhost:8000/login/',
    data: '{"username":"admin","password":"Kv79NExi"}'
  },
  request: <ref *1> ClientRequest {
    _events: [Object: null prototype] {
      abort: [Function (anonymous)],
      aborted: [Function (anonymous)],
      connect: [Function (anonymous)],
      error: [Function (anonymous)],
      socket: [Function (anonymous)],
      timeout: [Function (anonymous)],
      finish: [Function: requestOnFinish]
    },
    _eventsCount: 7,
    _maxListeners: undefined,
    outputData: [],
    outputSize: 0,
    writable: true,
    destroyed: false,
    _last: true,
    chunkedEncoding: false,
    shouldKeepAlive: false,
    maxRequestsOnConnectionReached: false,
    _defaultKeepAlive: true,
    useChunkedEncodingByDefault: true,
    sendDate: false,
    _removedConnection: false,
    _removedContLen: false,
    _removedTE: false,
    strictContentLength: false,
    _contentLength: '42',
    _hasBody: true,
    _trailer: '',
    finished: true,
    _headerSent: true,
    _closed: false,
    socket: <ref *2> Socket {
      connecting: false,
      _hadError: false,
      _parent: null,
      _host: 'localhost',
      _closeAfterHandlingError: false,
      _readableState: ReadableState {
        objectMode: false,
        highWaterMark: 16384,
        buffer: BufferList { head: null, tail: null, length: 0 },
        length: 0,
        pipes: [],
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: true,
        constructed: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: false,
        errorEmitted: false,
        emitClose: false,
        autoDestroy: true,
        destroyed: false,
        errored: null,
        closed: false,
        closeEmitted: false,
        defaultEncoding: 'utf8',
        awaitDrainWriters: null,
        multiAwaitDrain: false,
        readingMore: false,
        dataEmitted: true,
        decoder: null,
        encoding: null,
        [Symbol(kPaused)]: false
      },
      _events: [Object: null prototype] {
        end: [Function: onReadableStreamEnd],
        free: [Function: onFree],
        close: [ [Function: onClose], [Function: socketCloseListener] ],
        timeout: [Function: onTimeout],
        agentRemove: [Function: onRemove],
        error: [Function: socketErrorListener],
        finish: [Function: bound onceWrapper] { listener: [Function: destroy] }
      },
      _eventsCount: 7,
      _maxListeners: undefined,
      _writableState: WritableState {
        objectMode: false,
        highWaterMark: 16384,
        finalCalled: true,
        needDrain: false,
        ending: true,
        ended: true,
        finished: false,
        destroyed: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function: bound onwrite],
        writecb: null,
        writelen: 0,
        afterWriteTickInfo: null,
        buffered: [],
        bufferedIndex: 0,
        allBuffers: true,
        allNoop: true,
        pendingcb: 1,
        constructed: true,
        prefinished: false,
        errorEmitted: false,
        emitClose: false,
        autoDestroy: true,
        errored: null,
        closed: false,
        closeEmitted: false,
        [Symbol(kOnFinished)]: []
      },
      allowHalfOpen: false,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: null,
      _server: null,
      parser: null,
      _httpMessage: [Circular *1],
      [Symbol(async_id_symbol)]: 969,
      [Symbol(kHandle)]: TCP {
        reading: true,
        onconnection: null,
        [Symbol(owner_symbol)]: [Circular *2]
      },
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]: null,
      [Symbol(kBuffer)]: null,
      [Symbol(kBufferCb)]: null,
      [Symbol(kBufferGen)]: null,
      [Symbol(kCapture)]: false,
      [Symbol(kSetNoDelay)]: true,
      [Symbol(kSetKeepAlive)]: true,
      [Symbol(kSetKeepAliveInitialDelay)]: 60,
      [Symbol(kBytesRead)]: 0,
      [Symbol(kBytesWritten)]: 0
    },
    _header: 'POST /login/ HTTP/1.1rn' +
      'Accept: application/json, text/plain, */*rn' +
      'Content-Type: application/jsonrn' +
      'X-CSRFToken: 9aSiDra8P3LzU0hMlSFZ9yqX5fllDySQljBRyHM6jjSYfuZ1BWrCUF9blkElzl1vrn' +
      'User-Agent: axios/1.7.9rn' +
      'Content-Length: 42rn' +
      'Accept-Encoding: gzip, compress, deflate, brrn' +
      'Host: localhost:8000rn' +
      'Connection: closern' +
      'rn',
    _keepAliveTimeout: 0,
    _onPendingData: [Function: nop],
    agent: Agent {
      _events: [Object: null prototype] {
        free: [Function (anonymous)],
        newListener: [Function: maybeEnableKeylog]
      },
      _eventsCount: 2,
      _maxListeners: undefined,
      defaultPort: 80,
      protocol: 'http:',
      options: [Object: null prototype] { noDelay: true, path: null },
      requests: [Object: null prototype] {},
      sockets: [Object: null prototype] {
        'localhost:8000:': [
          <ref *2> Socket {
            connecting: false,
            _hadError: false,
            _parent: null,
            _host: 'localhost',
            _closeAfterHandlingError: false,
            _readableState: [ReadableState],
            _events: [Object: null prototype],
            _eventsCount: 7,
            _maxListeners: undefined,
            _writableState: [WritableState],
            allowHalfOpen: false,
            _sockname: null,
            _pendingData: null,
            _pendingEncoding: '',
            server: null,
            _server: null,
            parser: null,
            _httpMessage: [Circular *1],
            [Symbol(async_id_symbol)]: 969,
            [Symbol(kHandle)]: [TCP],
            [Symbol(lastWriteQueueSize)]: 0,
            [Symbol(timeout)]: null,
            [Symbol(kBuffer)]: null,
            [Symbol(kBufferCb)]: null,
            [Symbol(kBufferGen)]: null,
            [Symbol(kCapture)]: false,
            [Symbol(kSetNoDelay)]: true,
            [Symbol(kSetKeepAlive)]: true,
            [Symbol(kSetKeepAliveInitialDelay)]: 60,
            [Symbol(kBytesRead)]: 0,
            [Symbol(kBytesWritten)]: 0
          }
        ]
      },
      freeSockets: [Object: null prototype] {},
      keepAliveMsecs: 1000,
      keepAlive: false,
      maxSockets: Infinity,
      maxFreeSockets: 256,
      scheduling: 'lifo',
      maxTotalSockets: Infinity,
      totalSocketCount: 1,
      [Symbol(kCapture)]: false
    },
    socketPath: undefined,
    method: 'POST',
    maxHeaderSize: undefined,
    insecureHTTPParser: undefined,
    path: '/login/',
    _ended: true,
    res: IncomingMessage {
      _readableState: ReadableState {
        objectMode: false,
        highWaterMark: 16384,
        buffer: BufferList { head: null, tail: null, length: 0 },
        length: 0,
        pipes: [],
        flowing: true,
        ended: true,
        endEmitted: true,
        reading: false,
        constructed: true,
        sync: true,
        needReadable: false,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: false,
        errorEmitted: false,
        emitClose: true,
        autoDestroy: true,
        destroyed: true,
        errored: null,
        closed: true,
        closeEmitted: true,
        defaultEncoding: 'utf8',
        awaitDrainWriters: null,
        multiAwaitDrain: false,
        readingMore: true,
        dataEmitted: true,
        decoder: null,
        encoding: null,
        [Symbol(kPaused)]: false
      },
      _events: [Object: null prototype] {
        end: [ [Function: responseOnEnd], [Function: handleStreamEnd] ],
        error: [Function: handleStreamError],
        data: [Function: handleStreamData],
        aborted: [Function: handlerStreamAborted]
      },
      _eventsCount: 4,
      _maxListeners: undefined,
      socket: <ref *2> Socket {
        connecting: false,
        _hadError: false,
        _parent: null,
        _host: 'localhost',
        _closeAfterHandlingError: false,
        _readableState: ReadableState {
          objectMode: false,
          highWaterMark: 16384,
          buffer: BufferList { head: null, tail: null, length: 0 },
          length: 0,
          pipes: [],
          flowing: true,
          ended: false,
          endEmitted: false,
          reading: true,
          constructed: true,
          sync: false,
          needReadable: true,
          emittedReadable: false,
          readableListening: false,
          resumeScheduled: false,
          errorEmitted: false,
          emitClose: false,
          autoDestroy: true,
          destroyed: false,
          errored: null,
          closed: false,
          closeEmitted: false,
          defaultEncoding: 'utf8',
          awaitDrainWriters: null,
          multiAwaitDrain: false,
          readingMore: false,
          dataEmitted: true,
          decoder: null,
          encoding: null,
          [Symbol(kPaused)]: false
        },
        _events: [Object: null prototype] {
          end: [Function: onReadableStreamEnd],
          free: [Function: onFree],
          close: [ [Function: onClose], [Function: socketCloseListener] ],
          timeout: [Function: onTimeout],
          agentRemove: [Function: onRemove],
          error: [Function: socketErrorListener],
          finish: [Function: bound onceWrapper] {
            listener: [Function: destroy]
          }
        },
        _eventsCount: 7,
        _maxListeners: undefined,
        _writableState: WritableState {
          objectMode: false,
          highWaterMark: 16384,
          finalCalled: true,
          needDrain: false,
          ending: true,
          ended: true,
          finished: false,
          destroyed: false,
          decodeStrings: false,
          defaultEncoding: 'utf8',
          length: 0,
          writing: false,
          corked: 0,
          sync: false,
          bufferProcessing: false,
          onwrite: [Function: bound onwrite],
          writecb: null,
          writelen: 0,
          afterWriteTickInfo: null,
          buffered: [],
          bufferedIndex: 0,
          allBuffers: true,
          allNoop: true,
          pendingcb: 1,
          constructed: true,
          prefinished: false,
          errorEmitted: false,
          emitClose: false,
          autoDestroy: true,
          errored: null,
          closed: false,
          closeEmitted: false,
          [Symbol(kOnFinished)]: []
        },
        allowHalfOpen: false,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: null,
        _server: null,
        parser: null,
        _httpMessage: [Circular *1],
        [Symbol(async_id_symbol)]: 969,
        [Symbol(kHandle)]: TCP {
          reading: true,
          onconnection: null,
          [Symbol(owner_symbol)]: [Circular *2]
        },
        [Symbol(lastWriteQueueSize)]: 0,
        [Symbol(timeout)]: null,
        [Symbol(kBuffer)]: null,
        [Symbol(kBufferCb)]: null,
        [Symbol(kBufferGen)]: null,
        [Symbol(kCapture)]: false,
        [Symbol(kSetNoDelay)]: true,
        [Symbol(kSetKeepAlive)]: true,
        [Symbol(kSetKeepAliveInitialDelay)]: 60,
        [Symbol(kBytesRead)]: 0,
        [Symbol(kBytesWritten)]: 0
      },
      httpVersionMajor: 1,
      httpVersionMinor: 1,
      httpVersion: '1.1',
      complete: true,
      rawHeaders: [
        'date',
        'Fri, 06 Dec 2024 19:03:51 GMT',
        'server',
        'uvicorn',
        'content-type',
        'text/html; charset=utf-8',
        'x-frame-options',
        'DENY',
        'content-length',
        '3092',
        'vary',
        'origin',
        'x-content-type-options',
        'nosniff',
        'referrer-policy',
        'same-origin',
        'connection',
        'close'
      ],
      rawTrailers: [],
      aborted: false,
      upgrade: false,
      url: '',
      method: null,
      statusCode: 403,
      statusMessage: 'Forbidden',
      client: <ref *2> Socket {
        connecting: false,
        _hadError: false,
        _parent: null,
        _host: 'localhost',
        _closeAfterHandlingError: false,
        _readableState: ReadableState {
          objectMode: false,
          highWaterMark: 16384,
          buffer: BufferList { head: null, tail: null, length: 0 },
          length: 0,
          pipes: [],
          flowing: true,
          ended: false,
          endEmitted: false,
          reading: true,
          constructed: true,
          sync: false,
          needReadable: true,
          emittedReadable: false,
          readableListening: false,
          resumeScheduled: false,
          errorEmitted: false,
          emitClose: false,
          autoDestroy: true,
          destroyed: false,
          errored: null,
          closed: false,
          closeEmitted: false,
          defaultEncoding: 'utf8',
          awaitDrainWriters: null,
          multiAwaitDrain: false,
          readingMore: false,
          dataEmitted: true,
          decoder: null,
          encoding: null,
          [Symbol(kPaused)]: false
        },
        _events: [Object: null prototype] {
          end: [Function: onReadableStreamEnd],
          free: [Function: onFree],
          close: [ [Function: onClose], [Function: socketCloseListener] ],
          timeout: [Function: onTimeout],
          agentRemove: [Function: onRemove],
          error: [Function: socketErrorListener],
          finish: [Function: bound onceWrapper] {
            listener: [Function: destroy]
          }
        },
        _eventsCount: 7,
        _maxListeners: undefined,
        _writableState: WritableState {
          objectMode: false,
          highWaterMark: 16384,
          finalCalled: true,
          needDrain: false,
          ending: true,
          ended: true,
          finished: false,
          destroyed: false,
          decodeStrings: false,
          defaultEncoding: 'utf8',
          length: 0,
          writing: false,
          corked: 0,
          sync: false,
          bufferProcessing: false,
          onwrite: [Function: bound onwrite],
          writecb: null,
          writelen: 0,
          afterWriteTickInfo: null,
          buffered: [],
          bufferedIndex: 0,
          allBuffers: true,
          allNoop: true,
          pendingcb: 1,
          constructed: true,
          prefinished: false,
          errorEmitted: false,
          emitClose: false,
          autoDestroy: true,
          errored: null,
          closed: false,
          closeEmitted: false,
          [Symbol(kOnFinished)]: []
        },
        allowHalfOpen: false,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: null,
        _server: null,
        parser: null,
        _httpMessage: [Circular *1],
        [Symbol(async_id_symbol)]: 969,
        [Symbol(kHandle)]: TCP {
          reading: true,
          onconnection: null,
          [Symbol(owner_symbol)]: [Circular *2]
        },
        [Symbol(lastWriteQueueSize)]: 0,
        [Symbol(timeout)]: null,
        [Symbol(kBuffer)]: null,
        [Symbol(kBufferCb)]: null,
        [Symbol(kBufferGen)]: null,
        [Symbol(kCapture)]: false,
        [Symbol(kSetNoDelay)]: true,
        [Symbol(kSetKeepAlive)]: true,
        [Symbol(kSetKeepAliveInitialDelay)]: 60,
        [Symbol(kBytesRead)]: 0,
        [Symbol(kBytesWritten)]: 0
      },
      _consuming: false,
      _dumped: false,
      req: [Circular *1],
      responseUrl: 'http://localhost:8000/login/',
      redirects: [],
      [Symbol(kCapture)]: false,
      [Symbol(kHeaders)]: {
        date: 'Fri, 06 Dec 2024 19:03:51 GMT',
        server: 'uvicorn',
        'content-type': 'text/html; charset=utf-8',
        'x-frame-options': 'DENY',
        'content-length': '3092',
        vary: 'origin',
        'x-content-type-options': 'nosniff',
        'referrer-policy': 'same-origin',
        connection: 'close'
      },
      [Symbol(kHeadersCount)]: 18,
      [Symbol(kTrailers)]: null,
      [Symbol(kTrailersCount)]: 0
    },
    aborted: false,
    timeoutCb: null,
    upgradeOrConnect: false,
    parser: null,
    maxHeadersCount: null,
    reusedSocket: false,
    host: 'localhost',
    protocol: 'http:',
    _redirectable: Writable {
      _writableState: WritableState {
        objectMode: false,
        highWaterMark: 16384,
        finalCalled: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        destroyed: false,
        decodeStrings: true,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: true,
        bufferProcessing: false,
        onwrite: [Function: bound onwrite],
        writecb: null,
        writelen: 0,
        afterWriteTickInfo: null,
        buffered: [],
        bufferedIndex: 0,
        allBuffers: true,
        allNoop: true,
        pendingcb: 0,
        constructed: true,
        prefinished: false,
        errorEmitted: false,
        emitClose: true,
        autoDestroy: true,
        errored: null,
        closed: false,
        closeEmitted: false,
        [Symbol(kOnFinished)]: []
      },
      _events: [Object: null prototype] {
        response: [Function: handleResponse],
        error: [Function: handleRequestError],
        socket: [Function: handleRequestSocket]
      },
      _eventsCount: 3,
      _maxListeners: undefined,
      _options: {
        maxRedirects: 21,
        maxBodyLength: Infinity,
        protocol: 'http:',
        path: '/login/',
        method: 'POST',
        headers: [Object: null prototype] {
          Accept: 'application/json, text/plain, */*',
          'Content-Type': 'application/json',
          'X-CSRFToken': '9aSiDra8P3LzU0hMlSFZ9yqX5fllDySQljBRyHM6jjSYfuZ1BWrCUF9blkElzl1v',
          'User-Agent': 'axios/1.7.9',
          'Content-Length': '42',
          'Accept-Encoding': 'gzip, compress, deflate, br'
        },
        agents: { http: undefined, https: undefined },
        auth: undefined,
        family: undefined,
        beforeRedirect: [Function: dispatchBeforeRedirect],
        beforeRedirects: { proxy: [Function: beforeRedirect] },
        hostname: 'localhost',
        port: '8000',
        agent: undefined,
        nativeProtocols: {
          'http:': {
            _connectionListener: [Function: connectionListener],
            METHODS: [Array],
            STATUS_CODES: [Object],
            Agent: [Function],
            ClientRequest: [Function: ClientRequest],
            IncomingMessage: [Function: IncomingMessage],
            OutgoingMessage: [Function: OutgoingMessage],
            Server: [Function: Server],
            ServerResponse: [Function: ServerResponse],
            createServer: [Function: createServer],
            validateHeaderName: [Function: __node_internal_],
            validateHeaderValue: [Function: __node_internal_],
            get: [Function: get],
            request: [Function: request],
            setMaxIdleHTTPParsers: [Function: setMaxIdleHTTPParsers],
            maxHeaderSize: [Getter],
            globalAgent: [Getter/Setter]
          },
          'https:': {
            Agent: [Function: Agent],
            globalAgent: [Agent],
            Server: [Function: Server],
            createServer: [Function: createServer],
            get: [Function: get],
            request: [Function: request]
          }
        },
        pathname: '/login/'
      },
      _ended: true,
      _ending: true,
      _redirectCount: 0,
      _redirects: [],
      _requestBodyLength: 42,
      _requestBodyBuffers: [],
      _onNativeResponse: [Function (anonymous)],
      _currentRequest: [Circular *1],
      _currentUrl: 'http://localhost:8000/login/',
      [Symbol(kCapture)]: false
    }, 
    .
    .
    .
    data: 'n' +
      '<!DOCTYPE html>n' +
      '<html lang="en">n' +
      '<head>n' +
      '  <meta http-equiv="content-type" content="text/html; charset=utf-8">n' +
      '  <meta name="robots" content="NONE,NOARCHIVE">n' +
      '  <title>403 Forbidden</title>n' +
      '  <style type="text/css">n' +
      '    html * { padding:0; margin:0; }n' +
      '    body * { padding:10px 20px; }n' +
      '    body * * { padding:0; }n' +
      '    body { font:small sans-serif; background:#eee; color:#000; }n' +
      '    body>div { border-bottom:1px solid #ddd; }n' +
      '    h1 { font-weight:normal; margin-bottom:.4em; }n' +
      '    h1 span { font-size:60%; color:#666; font-weight:normal; }n' +
      '    #info { background:#f6f6f6; }n' +
      '    #info ul { margin: 0.5em 4em; }n' +
      '    #info p, #summary p { padding-top:10px; }n' +
      '    #summary { background: #ffc; }n' +
      '    #explanation { background:#eee; border-bottom: 0px none; }n' +
      '  </style>n' +
      '</head>n' +
      '<body>n' +
      '<div id="summary">n' +
      '  <h1>アクセス禁止 <span>(403)</span></h1>n' +
      '  <p>CSRF検証に失敗したため、リクエストは中断されました。</p>n' +
      'n' +
      'n' +
      '  <p>このメッセージが表示されている理由は、このサイトはフォーム送信時にCSRFクッキーを必須としているためです。このクッキーはセキュリティ上の理由(使用中のブラウザが第三者によってハイジャックされていないことを確認するため)で必要です。</p>n' +
      '  <p>もしブラウザのクッキーを無効に設定しているならば、same-originリクエストのために少なくともこのサイトでは再度有効にしてください。</p>n' +
      'n' +
      '</div>n' +
      'n' +
      '<div id="info">n' +
      '  <h2>Help</h2>n' +
      '    n' +
      '    <p>Reason given for failure:</p>n' +
      '    <pre>n' +
      '    CSRF cookie not set.n' +
      '    </pre>n' +
      '    n' +
      'n' +
      '  <p>In general, this can occur when there is a genuine Cross Site Request Forgery, or whenn' +
      '  <an' +
      '  href="https://docs.djangoproject.com/en/4.2/ref/csrf/">Django’sn' +
      '  CSRF mechanism</a> has not been used correctly.  For POST forms, you need ton' +
      '  ensure:</p>n' +
      'n' +
      '  <ul>n' +
      '    <li>Your browser is accepting cookies.</li>n' +
      'n' +
      '    <li>The view function passes a <code>request</code> to the template’s <an' +
      '    href="https://docs.djangoproject.com/en/dev/topics/templates/#django.template.backends.base.Template.render"><code>render</code></a>n' +
      '    method.</li>n' +
      'n' +
      '    <li>In the template, there is a <code>{% csrf_tokenn' +
      '    %}</code> template tag inside each POST form thatn' +
      '    targets an internal URL.</li>n' +
      'n' +
      '    <li>If you are not using <code>CsrfViewMiddleware</code>, then you must usen' +
      '    <code>csrf_protect</code> on any views that use the <code>csrf_token</code>n' +
      '    template tag, as well as those that accept the POST data.</li>n' +
      'n' +
      '    <li>The form has a valid CSRF token. After logging in in another browsern' +
      '    tab or hitting the back button after a login, you may need to reload then' +
      '    page with the form, because the token is rotated after a login.</li>n' +
      '  </ul>n' +
      'n' +
      '  <p>You’re seeing the help section of this page because you have <code>DEBUG =n' +
      '  True</code> in your Django settings file. Change that to <code>False</code>,n' +
      '  and only the initial error message will be displayed.  </p>n' +
      'n' +
      '  <p>You can customize this page using the CSRF_FAILURE_VIEW setting.</p>n' +
      '</div>n' +
      'n' +
      '</body>n' +
      '</html>n'
  },
  status: 403
}