4

So this is the first time I've used puppeteer for testing purposes. But I've run into a strange error when running the

what I'm trying to do is run this function in the page, however

const puppeteer = require('puppeteer');   
let browser, page,
//evaluates to file://C:/Users/chris/Google Drive/code projects/text translation sheet/test/src/index.html
    htmlFilepath = "file://" + path.resolve(__dirname, "src/index.html");
browser = await puppeteer.launch();
page = await browser.newPage();
await page.goto(htmlFilepath);   
page.exposeFunction(getMaxWordsInContentArea.name, getMaxWordsInContentArea)
      
const lastWordThatFit = await page.evaluate(function(){
          
    const el = document.querySelector('.line__target-language-text')
    const elContainer = el.parent;
    const lastFitWordIndex = getMaxWordsInContentArea(el,elContainer,["Call", "me", "Ishmael.", "Some", "years", "ago—never", "mind", "how", "long", "precisely—having", "little", "or", "no", "money", "in", "my", "purse,", "and", "nothing", "particular", "to", "interest", "me", "on", "shore,", "I", "thought", "I", "would", "sail", "about", "a", "little", "and", "see", "the", "watery", "part", "of", "the", "world.", "It", "is", "a", "way", "I", "have", "of", "driving", "off", "the", "spleen", "and", "regulating", "the", "circulation."])  
                    
    return lastFitWordIndex
});

Anybody see anything wrong with this or have familiarity with this error?

  • 1
    You're passing a function into the `.evaluate()` call where it expects a string. I would define that function elsewhere and then call it like `.evaluate(myFunction())` – Zen Monkey Nov 20 '20 at 01:50
  • That doesn't work. The logic that is inside the function needs to be executed inside the page. to get the function to be called when its inside the page is why the `evaluate` function is there.`evaluate()` is suppose to allow passing functions as per the docs here: https://github.com/puppeteer/puppeteer/blob/main/docs/api.md#pageevaluatepagefunction-args. anything else that looks like it might be causing a problem? – LeviathanTheDapper Nov 20 '20 at 02:05
  • I see, it is meant to evaluate the function you pass it. I would use a lambda function. This answer here pretty much shows you how to use it https://stackoverflow.com/questions/46088351/puppeteer-pass-variable-in-evaluate – Zen Monkey Nov 20 '20 at 02:16

1 Answers1

10

Forgot to include the await in front of page.exposeFunction(getMaxWordsInContentArea.name, getMaxWordsInContentArea).

Shoutout to @ZenMonkey for pushing me to dig deeper.