How to pass a function in Puppeteers .evaluate() method?

前端 未结 6 1543
后悔当初
后悔当初 2020-12-08 10:06

Whenever I try to pass a function, like this:

var myFunc = function() { console.log(\"lol\"); };

await page.evaluate(func => {
 func();
 return true;
},          


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-08 10:53

    Similar problems have been discussed in a puppeteer issue.

    There are several way to deal with your problem. First rule is to keep it simple.

    Evaluate the function

    This is the fastest way to do things, you can just pass the function and execute it.

    await page.evaluate(() => {
      var myFunc = function(element) { element.innerHTML = "baz" };
      var foo = document.querySelector('.bar');
      myFunc(foo);
      return true;
    });
    

    Expose the function beforehand

    You can expose the function beforehand using a page.evaluate, or a page.addScriptTag

    // add it manually and expose to window
    await page.evaluate(() => {
      window.myFunc = function(element) { element.innerHTML = "baz" };
    });
    
    // add some scripts
    await page.addScriptTag({path: "myFunc.js"});
    
    // Now I can evaluate as many times as I want
    await page.evaluate(() => {
      var foo = document.querySelector('.bar');
      myFunc(foo);
      return true;
    });
    

    Use ElementHandle

    page.$(selector)

    You can pass an element handle to .evaluate and make changes as you seem fit.

    const bodyHandle = await page.$('body');
    const html = await page.evaluate(body => body.innerHTML, bodyHandle);
    

    page.$eval

    You can target one element and make changes as you want.

    const html = await page.$eval('.awesomeSelector', e => {
    e.outerHTML = "whatever"
    });
    

    The trick is to read the docs and keep it simple.

提交回复
热议问题