如何动态注入函数以使用Puppeteer进行评估? [英] How can I dynamically inject functions to evaluate using Puppeteer?

查看:54
本文介绍了如何动态注入函数以使用Puppeteer进行评估?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为无头Chrome使用木偶.我希望在页面内评估一个使用其他功能部分的功能,该功能是在其他位置动态定义的.

I am using Puppeteer for headless Chrome. I wish to evaluate a function inside the page that uses parts of other functions, defined dynamically elsewhere.

下面的代码是一个最小的示例/证明.实际上, functionToInject() otherFunctionToInject()更复杂,并且需要页面DOM.

The code below is a minimal example / proof. In reality functionToInject() and otherFunctionToInject() are more complex and require the pages DOM.

const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(someURL);       

var functionToInject = function(){
    return 1+1;
}

var otherFunctionToInject = function(input){
    return 6
}

var data = await page.evaluate(function(functionToInject, otherFunctionToInject){
    console.log('woo I run inside a browser')
    return functionToInject() + otherFunctionToInject();
});

return data

运行代码时,我得到:

错误:评估失败:TypeError:functionToInject不是函数

Error: Evaluation failed: TypeError: functionToInject is not a function

我了解: functionToInject 没有传递到页面的JS上下文中.但是,如何将其传递到页面的JS上下文中?

Which I understand: functionToInject isn't being passed into the page's JS context. But how do I pass it into the page's JS context?

推荐答案

您可以使用 addScriptTag将功能添加到页面上下文 :

You can add function to page context with addScriptTag:

const browser = await puppeteer.launch();
const page = await browser.newPage();

function functionToInject (){
    return 1+1;
}

function otherFunctionToInject(input){
    return 6
}

await page.addScriptTag({ content: `${functionToInject} ${otherFunctionToInject}`});

var data = await page.evaluate(function(){
    console.log('woo I run inside a browser')
    return functionToInject() + otherFunctionToInject();
});

console.log(data);

await browser.close();

此示例是使用字符串连接解决此问题的肮脏方法.更干净的方法是在 addScriptTag 方法中使用 url path .

This example is a dirty way of solving this problem with string concatenation. More clean would be using a url or path in the addScriptTag method.

或使用 exposeFunction (但现在函​​数包装在Promise中):

Or use exposeFunction (but now functions are wrapped in Promise):

const browser = await puppeteer.launch();
const page = await browser.newPage();

var functionToInject = function(){
    return 1+1;
}

var otherFunctionToInject = function(input){
    return 6
}

await page.exposeFunction('functionToInject', functionToInject);
await page.exposeFunction('otherFunctionToInject', otherFunctionToInject);

var data = await page.evaluate(async function(){
    console.log('woo I run inside a browser')
    return await functionToInject() + await otherFunctionToInject();
});

console.log(data);

await browser.close();

这篇关于如何动态注入函数以使用Puppeteer进行评估?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆