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 暴露本地模块到浏览器

上一篇:《黑客大曝光:移动应用安全揭秘及防护措施》一1.3 我们的议题


下一篇:Linux 安装python 模块及库