15

Say the script has navigated to a certain page. How to execute a js function inside that script?

describe("TestSuite", () => {
  test("Login", async() => {
    await page.goto(APP);
    await page.waitForSelector("[name=loginForm]");
    await page.click("input[name=username]");
    await page.type("input[name=username]", user.username);
    await page.click("input[name=pwd]");
    await page.type("input[name=pwd]", user.pwd);
    await page.click("input[name=login]");
    await page.waitForSelector(".PageBodyVertical");

 // execute a js function x() here which is loaded with the page.

  }, 60000);
1
  • Add a click event that calls that function to a button then use page.click('that_button') Commented Jun 4, 2018 at 7:51

2 Answers 2

23

Use the .evaluate() function.

describe("TestSuite", () => {
  test("Login", async() => {
    await page.goto(APP);
    await page.waitForSelector("[name=loginForm]");
    await page.click("input[name=username]");
    await page.type("input[name=username]", user.username);
    await page.click("input[name=pwd]");
    await page.type("input[name=pwd]", user.pwd);
    await page.click("input[name=login]");
    await page.waitForSelector(".PageBodyVertical");

    await page.evaluate( function(){
      x();
    } );

  }, 60000);
Sign up to request clarification or add additional context in comments.

4 Comments

How do you pass a variable into that javascript?
@CodeGuru by searching on stackoverflow stackoverflow.com/a/46098448/5036031
await page.evaluate(() => fLogon()); getting undefined flogon on typecript
Create fake function from resolve error type script: Ex: function x() { return 'Fake func' }
3

Example with args:

let a1 = "hello";
let a2 = " world";

const browser = await puppeteer.launch({ headless: false });
const page = await browser.newPage();
await page.evaluate(function(a1, a2){
      console.log('msg: ' + a1 + a2); // This code runs in the page's context and returns the result
}, a1, a2);

Puppeteer evaluate docs: https://pptr.dev/api/puppeteer.page.evaluate

Note 1: In order to see the console print you need to add a listener
Note 2: In order to invoke your own functions within evaluate you need to expose the function

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.