How to make puppeteer do a javascript function

So I am trying to make puppeteer lunch a page and then put a token inside a local storage. .setItem not working it is just crushing my chromium.

so there is a page called discord and if you have a user token you can log in to the page with a script

So I found out that someone has made a script that you can past in the console and then when the code says "token here" you past your token and then it all happens

    let token = "your token";

function login(token) {
    setInterval(() => {
      document.body.appendChild(document.createElement `iframe`).contentWindow.localStorage.token = `"${token}"`
    }, 50);
    setTimeout(() => {
      location.reload();
    }, 2500);
  }

login(token);

This is the code.

so my idea is to make puppeteer run this code and then just login to the page after refresh

there is any option to do it? If there is no option I have though about another solution, maybe make puppeteer type in the console the whole code.


If you want to execute the JavaScript code in the browser context with Puppeteer, you need an evaluate method. For reference: https://github.com/puppeteer/puppeteer/blob/v10.4.0/docs/api.md#pageevaluatepagefunction-args or Google for similar and more user-friendly examples - there are plenty on web and SO.

Basically, to execute any JS code in a browser context, you put your code inside an evaluate method and it should look like this:

await page.evaluate(() => new Promise((resolve) => {
   // your browser JS code goes here
}

As for the cookies part, they should persist even after reload (haven't tested, but check this for reference: Cookies gone after reload Puppeteer => page.setCookie(...cookies)).

Also, maybe unrelated, but be careful that everything is alright legal-wise, because bots and bot-like behavior is frowned upon by many sites and in breach of their ToS.