Javascript

nodejs puppeteer 暴露本地模块到浏览器

本文主要是介绍nodejs puppeteer 暴露本地模块到浏览器,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
const puppeteer = require("puppeteer");

puppeteer
    .launch({
        executablePath: "C:/Program Files/Google/Chrome/Application/chrome.exe",
        defaultViewport: null,
        headless: false,
    })
    .then(async (browser) => {
        const page = await browser.newPage();
        await expose(page, "fs");
    })
    .catch((err) => {});

async function expose(page, name) {
    /** 暴露每个模块方法到浏览器 */
    const Require = async (name) => {
        const object = require(name);
        for (const key in object) {
            if (Object.hasOwnProperty.call(object, key)) {
                const element = object[key];
                if ((element && typeof element === "function") || typeof element?.default === "function") {
                    await page.exposeFunction(name + "_expose_" + key, element);
                }
            }
        }
    };
    await Require(name);
    /** 组装各个方法形成一个模块,并注入到 window 对象 */
    await page.evaluate((name) => {
        const keys = Reflect.ownKeys(window)
            .filter((key) => key.startsWith(name + "_expose_"))
            .map((key) => key.replace(name + "_expose_", ""));
        const object = {};
        for (const key of keys) {
            Reflect.set(object, key, window[name + "_expose_" + key]);
 
        }
        /** 组装成一个对象,并注入浏览器 */
        Reflect.set(window, name, object);
    }, name);
}

效果
在这里插入图片描述

这篇关于nodejs puppeteer 暴露本地模块到浏览器的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!