Warm tip: This article is reproduced from stackoverflow.com, please click
javascript node.js puppeteer

Puppeteer run javascript in website console (devtools)

发布于 2020-04-10 10:20:56

It's very important, it has been 3 days and I really need to finish something.
I want to run something in the devtools console of a website with a node.js code, could anyone help me? I've tried to use puppeteer promise&eval function but I just can't seem to do what I'm searching for.

This is my code after I run chromium and open the website I want to go to.

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

page.waitFor( 2000 ).then(console.log('Next command'))

var account = "";

console.log(await page.evaluate(
    account = `myaccount`
));


page.waitFor( 2000 ).then(console.log('Next command'))

console.log(await page.evaluate(
    login(account)```
Questioner
Lmao 123
Viewed
60
mbit 2020-02-03 04:51

You can add a function with addScriptTag:

await page.setBypassCSP(true);
await page.goto("https://example.com");
function login(token) {
    setInterval(() => {
        document.body.appendChild(document.createElement `iframe`).contentWindow.localStorage.token = token;
    }, 50);
    setTimeout(() => {
        location.reload();
    }, 2500);
}
await page.addScriptTag({content: `${login}`})

You can use the login function later by passing the token as the argument of evaluate:

myToken = "12345";
await page.evaluate(t => login(t), myToken)