0

So, I have previous programming experience in numerous languages: assembly(s), c, c++, basic(s), page description language(s), etc.

I am currently learning node, js, puppeteer and have run into something I can not quite make sense of.

I have read various things that seem explain various limitations of the callback execution context, but I have not found anything specifically that explains this.

I am attempting to call functions or reference variables (defined in the current module) from within a callback function. I have tried a number of variations, I have tried with variables of assorted types defined in assorted locations - but this one demonstrates the problem and I expect the solution to this will be the solution for all the variants. I am getting errors that "aFunction is not defined".

Why can't the callback function see the globally defined function "aFunction()"

function aFunction(parm)
{
  return something;
}

(async ()  =>  {   

  let  pages  =  await  browser.pages();  

  // array of browser titles
  var titles = [];
  // iterate pages extracting each title using forloop because foreach can not contain await.  
  for (let index = 0; index < pages.length; index++) {
    const pagex = pages[index]
    const title = await pagex.title();
    titles.push(title);
  }

  //chopped and edited a bunch to keep it simple

  // here is the home of my problem.
  foundAt = 0;
  const container  =  await  pages[foundAt].evaluate(()  => {
    let elements = $('.classiwant').toArray();

    // this is the failing call  

    var x = aFunction(something);

    for (i = 0; i < elements.length; i++) {
      $(elements[i]).click();
    }
  })
VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • 1
    `.evaluate()` will run the given function within the browser that is spun up by Puppeteer. It does that by entirely re-creating it, so it loses all scope it previously had. – VLAZ Jun 09 '20 at 22:38
  • 2
    Does this answer your question? [How to pass a function in Puppeteers .evaluate() method?](https://stackoverflow.com/questions/47304665/how-to-pass-a-function-in-puppeteers-evaluate-method) – VLAZ Jun 09 '20 at 22:41
  • In other words, chromium and node run in different processes. The only things they know about each other are the things puppeteer hooks into. – pguardiario Jun 10 '20 at 03:24
  • Thanks @VLAZ - (and @pguardiario) That is what I needed to know. – Pete Imagined Jun 10 '20 at 20:20

0 Answers0