How do I reference js and css files from local library for IntroJs

I have a python 2.7 project that uses IntroJs 7. IntroJs just upgraded to a version 8 and it broke, with no warning, the functionality. I need to access 2 files from version 7, Intro.js and Introjs.css. I used to access them externally with this code on a webpage:

<link rel="stylesheet" href="https://unpkg.com/intro.js/introjs.css"/>
    <script src="https://unpkg.com/intro.js/intro.js"></script>

They changed those public access files from version 7 to 8 so those links cannot be used. To deal with it I imported the provided downloadable library from IntroJs. There are many files in it, including theme css options. However the key files intro.js and introjs.css do not exist in that library. Does anyone have experience using IntroJs from a local library and, if so, how do you call the intro.js and introjs.css files if they don’t exist in that library? I’ve downloaded the library from multiple places and those 2 files are never there.

I should add that the support for IntroJs is very vague about using the downloadable library and says nothing about calling intro.js and introjs.css locally. I’ve emailed them and they have been vague and unhelpful. Any help would be greatly appreciated.

image of introjs local library and how to call css and js files

Two paypal buttons [closed]

Is there an easy way to debug the paypal button? I recently made some javascript changes to a site and there’s an impact to the paypal button which may be related which caused there to be two paypal buttons on the checkout page. There are errors in the dev tools console of the browser but they are not super helpful. It has been many years since I have had to do anything serious with the paypal button, honestly it’s one of the more stable payment plugins to use.

loading html from another file gets blocked by oauth2 verification

Using .jsp to create a simple login functionality with oauth 2.0

I’m trying to load a navbar from another file into my login page, using jsp files and a javascript function:

<script>
        $(document).ready(function () {
            $("#navbar").load("navbar.jsp");
            console.log("testing testing");
        });
</script>

This creates the typical “Login with OAuth 2.0” in my navbar. I’ve changed my Antmatchers to accept ‘navbar.jsp’ as well.

@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf()
                    .disable()
                .antMatcher("/**")
                .authorizeRequests()    //problem in antmatchers whenever it sends me to sign in w google randomly       //added after example:
                .antMatchers("/", "views/navbar","/Login", "/Register", "/resources/", "/login/database", "/example/**","/public/**", "/resources/**","/resources/static/**")
                    .permitAll()
                .antMatchers("/**.js").permitAll()  //added this for navbar, not sure if works yet
                .anyRequest()
                    .authenticated()
                    .and()
                    .oauth2Login()  
                .and()
                    .logout()
                    .logoutUrl("/logout")
                    .logoutSuccessUrl("/");
    }
}

I’ve been researching for a while and cannot seem to find what I’m missing. Anything helps, thanks!

Javascript add event listner on Input if value change by other button [duplicate]

input event listener fires only when we type something in input, want to fire the event on click of button when values changes from outside

 const currentValue = document.querySelector('#currentValue');
        currentValue.addEventListener('input', function () {
          // This one fires only when we type something in input, want to fire this on click of button when values changes from outside
            console.log("Input alue changed!!");
        });

function myFunction() {
  console.log("Button Clicked..");
  currentValue.value = 3;
}
<input type="text" id="currentValue" value="1"/>
<button onclick="myFunction()">Test</button>

HTML Canvas, pulse animation from center position

I have created pulse animation using html canvas. There is two rectangles. Rectangle’s positions is updated dynamically. The smaller rectangle has pulse animation. I have problem calculate it’s center position value.
Without scaling I get correct position. But when scaling position is incorrect. How to calculate scaled X and Y?

HTML

<div class="wrap"></div>

JS

const canvas = document.createElement("canvas");
canvas.setAttribute("width", "500px");
canvas.setAttribute("height", "500px");
const ctx = canvas.getContext("2d");
const wrapper = document.getElementsByClassName("wrap")[0];
wrapper.appendChild(canvas);
let scale = 1;
let angle = 0;
const blockSize = 45; // Rectangle size
const pos = {x: 2, y: 1}; // Rectangle position

function anim(){
   ctx.clearRect(0, 0, canvas.width, canvas.height);
   ctx.setTransform(1, 0, 0, 1, 0, 0);
   draw(ctx, pos)
   update();
   requestAnimationFrame(anim);
}
anim();

function draw(ctx, position){
    ctx.fillStyle = "#000";
  ctx.fillRect((position.x * blockSize - blockSize), (position.y * blockSize - blockSize), blockSize, blockSize);
  
  // Smaller rectangle with pulse
  ctx.fillStyle = "red";
  const centerX = (position.x * blockSize - blockSize) / 2;
  const centerY = (position.y * blockSize - blockSize) / 2;
  const scaledX = centerX - (centerX * scale); 
  const scaledY = centerY - (centerY * scale);
  ctx.setTransform(scale, 0, 0, scale, centerX, scaledY);
  const recSize = 30;
  const x = (position.x * blockSize - blockSize) + ((blockSize - recSize) / 2);
  const y = (position.y * blockSize - blockSize) + ((blockSize - recSize) / 2);
  ctx.fillRect(x, y, recSize, recSize);
  ctx.setTransform(1, 0, 0, 1, 0, 0);
}

function update(){
    angle += Math.PI / 140;
  scale = 0.5 + Math.abs(Math.cos(angle));
}

const canvas = document.createElement("canvas");
canvas.setAttribute("width", "500px");
canvas.setAttribute("height", "500px");
const ctx = canvas.getContext("2d");
const wrapper = document.getElementsByClassName("wrap")[0];
wrapper.appendChild(canvas);
let scale = 1;
let angle = 0;
const blockSize = 45; // Rectangle size
const pos = {x: 2, y: 1}; // Rectangle position


function anim(){
   ctx.clearRect(0, 0, canvas.width, canvas.height);
   ctx.setTransform(1, 0, 0, 1, 0, 0);
   draw(ctx, pos)
   update();
   requestAnimationFrame(anim);
}
anim();

function draw(ctx, position){
    ctx.fillStyle = "#000";
  ctx.fillRect((position.x * blockSize - blockSize), (position.y * blockSize - blockSize), blockSize, blockSize);

  // Smaller rectangle with pulse
  ctx.fillStyle = "red";
  const centerX = (position.x * blockSize - blockSize) / 2;
  const centerY = (position.y * blockSize - blockSize) / 2;
  const scaledX = centerX - (centerX * scale); 
  const scaledY = centerY - (centerY * scale);
  ctx.setTransform(scale, 0, 0, scale, centerX, scaledY);
  const recSize = 30;
  const x = (position.x * blockSize - blockSize) + ((blockSize - recSize) / 2);
  const y = (position.y * blockSize - blockSize) + ((blockSize - recSize) / 2);
  ctx.fillRect(x, y, recSize, recSize);
  ctx.setTransform(1, 0, 0, 1, 0, 0);
}

function update(){
    angle += Math.PI / 140;
  scale = 0.5 + Math.abs(Math.cos(angle));
}
<div class="wrap">

</div>

Cant autofill the last 2 digits of card year in MUI React

I am trying to fix the autofill on my expiry input. It should autofill the last 2 digits of YYYY. Just YY.

I feel like I’m doing this right, but when I autofill it uses the first 2 digits, not the last 2.

Where am I going wrong?

<InputField
    id={id}
    name={'YY'}
    label={'YY'}
    placeholder='YY'
    maxlength="2"
    pattern="d{2}" 
    autoComplete='cc-exp-year'
/>

Vue breaks upon Object modification

If I do this:

Object.prototype.breakVue=true;

Vue will break.

How to avoid it?

More details (only if you want more context/details, first section is enough to reproduce the problem):

I wrote an Object plugin which injects many methods I wrote into every object by adding them into Object‘s prototype.
This works fine with plain JavaScript applications, but if I use Vue, it breaks it.
I use those handy methods in my code.
For example, if I want to make my class final, I do:

export default class FinalClass {}
FinalClass.makeFinal();

which is a handy shortcut for what I would usually have to type:

export default class FinalClass {}
Object.freeze(FinalClass);

and is made possible by injection of the makeFinal method into Object:

Object.prototype.makeFinal=function() { Object.freeze(this); }

I do have my own utility class:

export default class OBJECT { static makeFinal() { Object.freeze(this); } }

which I can use like this:

export default class FinalClass extends OBJECT {}
FinalClass.makeFinal();

but the downside is that all classes in which I want to use this have to extend from OBJECT, plus this does not work for objects which are not created by me. I want to be able to call my method on any object, so I want {}.makeFinal(); to be a valid syntax. Or "text".makeFinal(); and so on. So, I want all built in objects to have my extension methods injected.
Plus it is not just one extension function I wrote for Object. I have tens of them.

This works with plain JavaScript application. But now I want my extensions to be used with Web application which uses Vue. However, this does not work.

I have injected methods into many other JavaScript built in objects, such as Date and Vue worked without problems.

Do you know how to fix Vue? How to allow Vue to work, while allowing, for example, true.and(true); or 5.isGreaterThen(6); or {}.equals({}) to be a valid syntax in my code?

How to create better chunks to send openai

i have been creating a application which is connected to the drive from there they fetch the .docx file then i have converted the docx file into the html format so that LLM easily understand where is heading in the document but the problem i am facing is chunk creating

i tried to create chunk on the basis of bold formatting tags in the html file
for example such type of tag i consider for making chunks
strong html tag Buyer Management Procedure /strong

but the problem i faced is that when i got improved chunks from openai llm they gave me repeated content which i dont want

i tried everything but nothing works now i am clueless how to solve this probelm

CODE FOR CRREATING CHUNK

function processDocument(htmlContent) {
  console.log("Starting document processing...");
  const chunks = [];
  let customPrompts = {};

  // Process custom prompts across the entire document
  const processedContent = htmlContent.replace(/(([ws]+))((([ws]+)))/g, (match, text, prompt) => {
    customPrompts[text] = prompt;
    console.log(`Found custom prompt: "${text}" with instruction "${prompt}"`);
    return `(${text})`;
  });

  const dom = new JSDOM(processedContent);
  const document = dom.window.document;

  // Function to check if an element is a bold formatting tag
  function isBoldTag(element) {
    return ['H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'STRONG', 'B'].includes(element.tagName);
  }

  // Function to get heading level
  function getHeadingLevel(element) {
    if (element.tagName.startsWith('H')) {
      return parseInt(element.tagName.slice(1));
    }
    return 0; // For <strong> and <b> tags
  }

  let currentChunk = [];
  let currentHeading = '';
  let currentLevel = 0;

  function processNode(node) {
    if (node.nodeType === Node.ELEMENT_NODE) {
      if (isBoldTag(node)) {
        // If we have a current chunk, save it
        if (currentChunk.length > 0) {
          chunks.push({
            content: currentChunk.join(''),
            heading: currentHeading,
            level: currentLevel,
            customPrompts: { ...customPrompts }
          });
          currentChunk = [];
        }

        currentHeading = node.textContent;
        currentLevel = getHeadingLevel(node);
        currentChunk.push(node.outerHTML);
      } else {
        // For non-bold tags, just add their HTML to the current chunk
        currentChunk.push(node.outerHTML);
      }

      // Process child nodes
      node.childNodes.forEach(processNode);
    } else if (node.nodeType === Node.TEXT_NODE) {
      // Add text nodes to the current chunk
      currentChunk.push(node.textContent);
    }
  }

  // Start processing from the body
  processNode(document.body);

  // Add the last chunk if there's any content left
  if (currentChunk.length > 0) {
    chunks.push({
      content: currentChunk.join(''),
      heading: currentHeading,
      level: currentLevel,
      customPrompts: { ...customPrompts }
    });
  }

  console.log("Document processing complete.");
  console.log(`Total chunks created: ${chunks.length}`);

  // Log all chunks for visibility
  chunks.forEach((chunk, index) => {
    console.log(`nChunk ${index + 1}:`);
    console.log("Heading:", chunk.heading);
    console.log("Level:", chunk.level);
    console.log("Content:");
    console.log(chunk.content);
    console.log("Custom prompts:", chunk.customPrompts);
    console.log("Word count:", chunk.content.replace(/<[^>]*>/g, '').split(/s+/).filter(Boolean).length);
    console.log("-".repeat(50)); // Separator for readability
  });

  return chunks;
}
// Function to create an OpenAI assistant
async function createAssistant() {
  const assistant = await openai.beta.assistants.create({
    name: "Document Improvement Assistant",
    instructions:
      "You are an AI assistant that helps improve documents. Use the existing knowledge base to improve the content provided. Don't use any content from internet or your own knowledge. Enhance clarity, coherence, and relevance of the text. Use proper formatting and heading and make sure such text is improved. Don't add image placeholders or use links. Use simple text and don't use complex formatting. Use formatting which is good looking and readable, and provide detailed information.",
    model: "gpt-4o-mini",
    tools: [{ type: "file_search" }],
    tool_resources: {
      file_search: {
        vector_store_ids: [VECTOR_STORE_ID],
      },
    },
  });
  console.log(`Assistant created with ID: ${assistant.id}`);
  return assistant;
}

IMPROVMENT CHUNK CODE

async function improveChunk(chunk, fullDocument, assistantId, documentContext, customPromptInstruction, chunkIndex, totalChunks) {
console.log(Processing chunk ${chunkIndex + 1} of ${totalChunks});
const startTime = Date.now();

try {
const { content, customPrompts } = chunk;

let promptContent = `You are tasked with improving a chunk of text from a larger document. You will be provided with the following information:
  1. Document Context:
    ${documentContext}

  2. Custom Prompt Instruction:
    ${customPromptInstruction}

  3. The full document content:
    ${fullDocument}

  4. The current chunk of text to improve (chunk ${chunkIndex + 1} of ${totalChunks}):
    <current_chunk>${content}</current_chunk>

Your task is to improve the current chunk of text while ensuring continuity with the rest of the document and staying within the context. Follow these guidelines:

  1. It is CRUCIAL to avoid ANY repetition of information that exists elsewhere in the document. If you encounter content that appears elsewhere, you MUST either:
    a) Omit it to avoid repeatation
  2. Follow the custom prompt instruction provided above.
  3. If it’s a heading, format it correctly using Markdown syntax (e.g., # for main headings, ## for subheadings).
  4. Use Markdown formatting that is visually appealing and readable.
  5. Ensure smooth transitions with the surrounding content in the full document.
  6. also donot add such line This revision maintains continuity with the rest of the document while enhancing clarity and readability. The content has been organized into relevant categories, emphasizing the importance of buyers without introducing redundant information.
  7. if (#,*,##) any line start with such markdown syntax so elaborate that part

Additionally, there are specific parts of the text that require special attention. For each of these parts, enclosed in parentheses (), apply the corresponding custom prompt:

`;

for (const [text, prompt] of Object.entries(customPrompts)) {
  promptContent += `For the text "${text}": ${prompt}n`;
}

promptContent += `

Please provide the improved version of the current chunk, or indicate if it should be omitted due to redundancy:`;

const thread = await openai.beta.threads.create({
  messages: [{ role: "user", content: promptContent }],
  tool_resources: {
    file_search: { vector_store_ids: [VECTOR_STORE_ID] },
  },
});

const run = await openai.beta.threads.runs.create(thread.id, {
  assistant_id: assistantId,
});

let runStatus;
do {
  runStatus = await openai.beta.threads.runs.retrieve(thread.id, run.id);
  await new Promise((resolve) => setTimeout(resolve, 1000));
} while (runStatus.status !== "completed");

const messages = await openai.beta.threads.messages.list(thread.id);
const improvedChunk = messages.data[0].content[0].text.value;

if (improvedChunk.toLowerCase().includes("this chunk should be omitted")) {
  console.log(`Chunk ${chunkIndex + 1} suggested for omission due to redundancy.`);
  return null;
}

const endTime = Date.now();
const timeTaken = endTime - startTime;

const processData = new ProcessData({
  iterationNumber: fetchCounter,
  functionType: 'improve',
  chunk: content,
  aiPrompt: promptContent,
  openaiResponse: improvedChunk,
  timeTaken: timeTaken
});
await processData.save();

return improvedChunk;

} catch (error) {
console.error(Error improving chunk:, error);
return chunk.content;
}
}

How to find non reducible fractions more efficently(code keeps timing out)

I’m trying to find the non-reducible 0-1 fractions for a number passed as an argument in my function.
I was able to do this but my code keeps timing out for large numbers. Please help

function properFractions(n) {
  function gcd(a, b) {
    if (a == 0) return b;
    return gcd(b % a, a);
  }

  let result = 0;

  if (n === 1) {
    return result;
  } else if (n > 1) {
    for (let i = 1; i < n; i++) if (gcd(i, n) === 1) result++;
    return result;
  }
}

How to Ensure Database Update Only After Successful Document Printing in JavaScript?

I’m developing a web application where users can print documents from a browser. I need to ensure that a database update occurs only if the user actually prints the document, and not if they cancel or close the print dialog.

Problem Description
When a user initiates printing, I open a new window with the content to be printed. I want to:

  1. Trigger a database update only when the document is printed.
  2. Ensure that no database updates are made if the user cancels or closes the print dialog.

Current Approach
Here’s the approach I’m currently using:

  1. Open a new window with the document content to be printed.

  2. Attach an onafterprint event handler to this window to detect when the print dialog is
    closed.

  3. Use a timer to assume printing based on the time the print dialog is open.

    const handlePrint = async () => {
    const content = printRef.current.innerHTML;
    const printWindow = window.open(”, ”, ‘width=600,height=400’);
    let isPrintConfirmed = false;

    printWindow.document.write(<html> <head> <title>Print</title> <style> @media print { @page { margin: 0; } body { margin: 0; } .print-container { text-align: center; padding: 20px; } } </style> </head> <body> <div class="print-container"> ${content} </div> </body> </html>);

    printWindow.document.close();
    printWindow.focus();

    const confirmPrint = () => {
    if (!isPrintConfirmed) {
    isPrintConfirmed = true;
    const userConfirmed = window.confirm(“Did you successfully print the document?”);
    if (userConfirmed) {
    fetch(‘/api/updatePrintStatus’, {
    method: ‘POST’,
    body: JSON.stringify({ status: ‘printed’, guestId: guest.id }),
    headers: { ‘Content-Type’: ‘application/json’ },
    }).then(() => alert(“Database updated successfully.”))
    .catch(err => alert(“Error updating database: ” + err.message));
    } else {
    alert(“Print action was canceled or failed.”);
    }
    }
    };

    printWindow.onafterprint = confirmPrint;

    const printCheckTimer = setTimeout(() => {
    if (!isPrintConfirmed) {
    confirmPrint();
    }
    }, 5000);

    printWindow.print();
    printWindow.close();
    };

Issues Encountered

  • False Assumptions: If a user stays on the print dialog but does not actually print, the code might incorrectly assume printing occurred based on the timer.
  • Edge Cases: How can I improve handling to ensure that the database update happens only if the user actually prints?

Desired Solution
I am looking for a reliable way to:

  • Confirm if the user has actually printed the document.
  • Ensure that the database update only occurs if printing is confirmed.

Any advice on improving the current implementation or alternative approaches to achieve this would be greatly appreciated!

Adding a Front End to a REST API

I am struggling to figure out how to add a front end to my Rest API. I am Trying to Create a HTML page that dynamically changes based on what url is being visited. I currently get the JSON response from entering “/ListJokes” however i would like to convert this into a HTML page with a title and whatnot similar to “ListJokes.html”.

I briefly followed this Tutorial for context: https://www.freecodecamp.org/news/build-consume-and-document-a-rest-api/#how-to-build-a-rest-api-with-node-and-express

My ListJokes.html page:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>REST Client</title>
  </head>
  <body>
    <div id="joke-container">
      <h1 style="color:blueviolet; font-size: 60px; text-align: center;">All JOKES!</h1>
      <a href="http://localhost:5000/home"><button type="button">Home Page</button></a>
      <hr>
      <div id="joke-list">
      </div>
    </div>
  </body>
</html>

My index.html (homepage):

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>REST Client</title>
  </head>
  <body>
    <div class="container">
      <h1 style="color:blueviolet; font-size: 60px; text-align: center;">JOKE WEBISTE</h1>
      <hr>
      <div style="margin-bottom: 20px; margin-top: 20px; margin-left: 15px;">
        <a href="http://localhost:5000/jokes/ListJokes"><button type="button">LIST ALL JOKES!</button></a>
      </div>
      <form id="form" >
        <div style="margin-bottom: 20px; margin-top: 20px; margin-left: 15px;">
        <lable for="find joke id">ID: </lable>
        <input type="number" id="find joke id" name="find joke id" style="left: 20px; top: 10px;" placeholder="Enter Joke ID">
        <button type="submit" style="margin-left: 10px;">Find This Joke!</button>
        </div>
      </form>
    </div>
    <script type="module">
      
    </script>
  </body>
</html>

My Models.js script:

// This is the function definition file for the API. This will recieve data from the control file and will edit the Data Base or The HTML.

import Jokes from "./db.js" 

export const listItems = () => {
    try {
        console.log(Jokes)
        return Jokes                                                         //returns every joke in the Data Base
    } catch (err) {                                                              //added error handling
        console.log('Error', err)                                                //parses error message
    }
}

My Controller.js script:

// this file is the head controll file for the API. this will parse the HTTP requests to their corresponding JavaScript function in Models.js

import bodyparser from "body-parser";                     //Imports Body-Parser
import {
    getItem, listItems, editItem, addItem, deleteItem 
} from "./Models.js"                      //imports functions from Models.js

export const listJokes = (req, res) => {
    try {
        const resp = listItems()                                           //parses response into the function
        res.status(200)                                                    //sends "It Worked" Message when recieved
        res.send(JSON.stringify(resp))

    } catch (err) {                                                        //added error handling
        res.status(500).send(err)                                          //sends error message to client
    }
}

My Router.js script:

import express from "express";                            //Imports Express Framework
import bodyparser from "body-parser";                     //Imports Body-Parser
import path from "path";

import {
    listJokes,
    getJoke,
    editJoke,
    addJoke,
    deleteJoke,
} from "./Controller.js";          //imports function converter from controller.js

const router = express.Router();                                    //initialises the router

router.get("/listJokes", listJokes);                                //monitors endpoint and triggers converter

router.get("/ListJokes/:id", getJoke);                              //monitors endpoint and triggers converter

router.put("/editJoke/:id", editJoke);                              //monitors endpoint and triggers converter

router.post("/addJoke", addJoke);                                   //monitors endpoint and triggers converter

router.delete("/deleteJoke/:id", deleteJoke)                        //monitors endpoint and triggers converter



export default router;                                              //allows the router to be access remotely

My server.js script:

import router from "./Router.js"

import express from 'express'
import cors from 'cors'
import path from "path";

import { fileURLToPath } from 'url';
import { dirname } from 'path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const app = express()                                  //Starts App

app.use(cors())                                        //tells app to use cors
app.use(express.json())                                //tells app to use express to handle JSON files

app.use("/jokes", router)                          //tells app to use the routes from Router.js

app.listen(5000, () => {                               //Allow the server to scan port 5000 for requests
  console.log("Server is running on port 5000.");
});

app.get("/home", (req, res) => {
  res.sendFile(path.join(__dirname, "index.html"));    //Sends index.html file when "/home" is visited
});

export default app

I Have removed some functions/parts of the scripts that are not relevent as they follow the rough structure of the ones given. (This explains any random imports or anything like that). Any Help will be appreciated 🙂

Accessing GraphQL variables within network tab

I am using Graphql Apollo, React, and JS. We have form validation in our backend, when trying to display these errors on screen for better user experience, I cannot seem to find a way to access them. Within my browser console, the error I receive is just ‘ApolloError’, but within the network tab I can see the error message I’m trying to convey on the frontend. What is an easy way to access it? This is what I currently have as my code. Within ‘setAlerts’ that is the route to get to the error message if I were able to access the network tab. Thanks

 try {
                const { data } = await addUser({
                    variables: { username, email, password }, 
                })
                if (data.addUser === null) {

                    setAlerts(data.errors[0].message, "inline text-groove-red")
                }
                alert('Account creation successful!')
                Auth.login(data.addUser.token);
                navigate('/login')
            } catch (err) {
                console.error(err)
            }

enter image description here
enter image description here

Attempted to log ‘ApolloError’ as well as ‘data’. When I log data within my catch block it comes back as not defined.

JS puppeeter – changin IP by proxy

I’m working on a Node.js project where I’m trying to change my IP address using proxies with Puppeteer. However, when I open the Chromium browser window (in script), I still see my original IP address instead of the proxy IP. I’m relatively new to this, so any advice on how to properly configure the proxy would be greatly appreciated.

Here’s a simplified version of my code: ( some npm packages: )

antibotbrowser
puppeteer-extra
puppeteer-extra-plugin-stealth
async function switchProxy(proxies) { 
    while (!testPassed && proxies.length > 0) {
        proxy = proxies[Math.floor(Math.random() * proxies.length)];
        testPassed = await testProxyConnection(proxy);
    }
    return proxy;
}

async function testProxyConnection(proxy) {
    try {
        const protocol = proxy.protocol === 2 ? 'https' : 'http';
        
        const response = await axios.get('https://httpbin.org/ip', {
            proxy: {
                host: proxy.ip,
                port: proxy.port,
                protocol: protocol
            },
            timeout: 10000
        });

        const originIP = response.data.origin; 

        return true;
    } 
}

async function createBrowserWithProxyAndAntibot(proxy) {
    puppeteer.use(puppeteerExtraPluginStealth());
    const antibrowser = await antibotbrowser.startbrowser();

    const browser = await puppeteer.connect({
        browserWSEndpoint: antibrowser.websokcet,
        args: [
            --proxy-server=${proxy.protocol === 2 ? 'https' : 'http'}://${proxy.ip}:${proxy.port},
            '--disable-features=site-per-process',
            '--no-sandbox',
            '--disable-setuid-sandbox',
        ],
        headless: false,
    });

    const page = await browser.newPage();

    // CHECK IP - this print proxy IP
    const checkIP = await page.goto('https://httpbin.org/ip');
    const ipResult = await checkIP.json();
    console.log(Page IP: ${ipResult.origin});

    return { browser, page };
} 


(async () => {
    const proxies = await fetchProxiesFromAPI();
    const proxy = await switchProxy(proxies);  // Vyberte jeden funkční proxy

    const { browser, page } = await createBrowserWithProxyAndAntibot(proxy);

})();

I tried different proxy servers (free), modification of settings..

Puppeteer with Proxy Shows Original IP in Chromium Window

I’m working on a Node.js project where I’m trying to change my IP address using proxies with Puppeteer. However, when I open the Chromium browser window (in script), I still see my original IP address instead of the proxy IP. I’m relatively new to this, so any advice on how to properly configure the proxy would be greatly appreciated.

Here’s a simplified version of my code: ( some npm packages: )

antibotbrowser
puppeteer-extra
puppeteer-extra-plugin-stealth
async function switchProxy(proxies) { 
    while (!testPassed && proxies.length > 0) {
        proxy = proxies[Math.floor(Math.random() * proxies.length)];
        testPassed = await testProxyConnection(proxy);
    }
    return proxy;
}

async function testProxyConnection(proxy) {
    try {
        const protocol = proxy.protocol === 2 ? 'https' : 'http';
        
        const response = await axios.get('https://httpbin.org/ip', {
            proxy: {
                host: proxy.ip,
                port: proxy.port,
                protocol: protocol
            },
            timeout: 10000
        });

        const originIP = response.data.origin; 

        return true;
    } 
}

async function createBrowserWithProxyAndAntibot(proxy) {
    puppeteer.use(puppeteerExtraPluginStealth());
    const antibrowser = await antibotbrowser.startbrowser();

    const browser = await puppeteer.connect({
        browserWSEndpoint: antibrowser.websokcet,
        args: [
            `--proxy-server=${proxy.protocol === 2 ? 'https' : 'http'}://${proxy.ip}:${proxy.port}`,
            '--disable-features=site-per-process',
            '--no-sandbox',
            '--disable-setuid-sandbox',
        ],
        headless: false,
    });

    const page = await browser.newPage();

    // CHECK IP - this print proxy IP
    const checkIP = await page.goto('https://httpbin.org/ip');
    const ipResult = await checkIP.json();
    console.log(`Page IP: ${ipResult.origin}`);

    return { browser, page };
} 


(async () => {
    const proxies = await fetchProxiesFromAPI();
    const proxy = await switchProxy(proxies);  // Vyberte jeden funkční proxy

    const { browser, page } = await createBrowserWithProxyAndAntibot(proxy);

})();

Set a default position on a map using js – WordPress theme file

I try to create a wordpress directory website for french schools.

I have one issue, my theme “map service” do not allow me to define a default position on the map when it load. It automatically calcul the center point of all my markers and I don’t want that because of the french islands based all around the globe. I need the map to be, by default, centered on Metropolitan France (Latitude : 46.227638 ; Longitude : 2.213749).

I tried to reach the theme developpers but they are not willing to help me so I tried the whole afternoon to find a solution by my own but I barely can read Javascript so all my modifications attempts failed…

If there is anyone with a bit of time to analyse the theme file that load the map (HERE is the file) I would love to have some help, it would mean a lot!

My apologies for my bad english.

Thanks by advance to everyone that took some times to read my message.

Jonathan