javascript - 如何在 puppeteer 中访问全局变量

标签 javascript puppeteer

在这个示例代码中,当它读取数组 contactListj 时,它说两者都没有定义,有什么问题吗?


const { join } = require('path');
const puppeteer = require('puppeteer');

(async () => {

    // 1. Launch the browser
    const browser = await puppeteer.launch({   
          "args": [
              '--remote-debugging-port=9222'
          ],
          "defaultViewport": {
            "height": 1080,
            "width": 1920
          },
          "headless": false
        });

    // 2. Open a new page
    const page = await browser.newPage();

    // 3. Navigate to URL
    await page.goto('https://');

    await new Promise(r => setTimeout(r, 10000));
    console.log('Ready');

    var contactList = ['cesar','gab','777','81411579','34353'];
    var fLen = contactList.length;
    var j = 0;

    for (i = 0; i < fLen; i++) {

        await page.evaluate(() => {

            function searchContact(contact_name = "") {
                //search = document.querySelector('#side > div._1Ra05 > div > label > div > div._1awRl.copyable-text.selectable-text');
                search = document.querySelector('#side > div._1Ra05 > div > label > div > div._1awRl.copyable-text.selectable-text');
            }
            j++;
            searchContact(contactList[j]);

        }
    }

最佳答案

查看 page.evaluate(pageFunction[,...args]) 的 Puppeteer 文档.它指出:

pageFunction <function|string> Function to be evaluated in the page context

注意(粗体)“在页面上下文中评估”。页面上下文中不存在变量 jcontactList

幸运的是,Puppeteer 有一种从页面上下文调用服务器端代码的方法 page.exposeFunction(name, puppeteerFunction)

The method adds a function called name on the page's window object. When called, the function executes puppeteerFunction in node.js and returns a Promise which resolves to the return value of puppeteerFunction.

对于您的用例,它看起来类似于以下内容:

const puppeteer = require('puppeteer');

(async function()
{
    const browser = await puppeteer.launch({
        headless: false,
        args: [
            "--no-sandbox", // I needed these args for it to run on my machine, you probably don't need them.
            "--disable-setuid-sandbox"
        ]
    });
    const page = await browser.newPage();
    const contacts = ["Charlie", "Carl", "Dennis", "Conrad"];
    await page.exposeFunction("getContacts", function()
    {
        return contacts;
    });
    await page.exposeFunction("addContact", function(contact)
    {
        contacts.push(contact);
    });
    await page.evaluate(async function()
    {
        await addContact("Henry");
        await addContact("Olav");
        const contacts = await getContacts();
        contacts.forEach(function(contact)
        {
            const div = document.createElement("div");
            div.innerHTML = contact;
            document.body.appendChild(div);
        });
    });
    console.log("Contacts after evaluating page function: ", contacts.join(", "));
})()

请注意,这是一个玩具示例,虽然是一个完整且可运行的示例。您应该能够从中找出其余部分。您在 OP 示例中发布的代码没有多大意义(即无限递归函数 searchContact()),因此您只需要根据您的用例进行调整。

关于javascript - 如何在 puppeteer 中访问全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65266253/

相关文章:

javascript - 如何在 Puppeteer 中查找 document.activeElement

node.js - 是否有一种通用方法可以使用 Puppeteer 消除所有模式和 cookie 警告?

javascript - jQuery .on() 不触发事件处理程序

javascript - 我被困在 javascript 中,隐藏/激活选定的选项卡

javascript - Google map 如何修复 OVER_QUERY_LIMIT 错误

node.js - 如何使用 Puppeteer 将(长)文本从剪贴板粘贴到 Textarea

selenium - headless 谷歌浏览器 : How to prevent sites to know whether their window is focused or not

javascript - 我们可以使用 jquery 向上一级节点吗?

javascript - jQuery - 如何使用 e.preventDefault();在 JavaScript 函数中

node.js - 在云功能上使用puppeteer拒绝了网站访问