如何使用Puppeteer检测网站是否存在指定JavaScript函数
Question
I'm working with Puppeteer and have code that currently executes a function test() on a target page, but I want to only check if the function exists (returning a boolean) instead of running it directly. Here's my current code:
'use strict'; const puppeteer = require('puppeteer'); (async function main() { try { const browser = await puppeteer.launch(); const [page] = await browser.pages(); await page.goto('https://vsemozhetbyt.github.io/test/test.html'); console.log(await page.evaluate(() => test())); await browser.close(); } catch (err) { console.error(err); } })();
The line console.log(await page.evaluate(() => test())); runs the test() function immediately if it exists. How can I modify this line to just detect if test() exists and return a boolean instead?
Answer
Great question! You can check for the function's existence by verifying its presence on the window object (where global functions live in browsers) and confirming its type is function—this avoids executing the function entirely.
Replace your existing console.log line with this:
console.log(await page.evaluate(() => typeof window.test === 'function'));
Breakdown:
typeof window.testreturns a string describing the type of thetestproperty. Iftestis a function, it will return'function'; if the property doesn't exist, it returns'undefined'; if it's a non-function variable, it returns the appropriate type (like'string'or'number').- Comparing this to
'function'gives you a clean boolean result indicating whether the function exists.
If you want an extra layer of safety (to ensure test is explicitly a property of window), you can combine the in operator with the type check:
console.log(await page.evaluate(() => 'test' in window && typeof window.test === 'function'));
This first checks if test is a property of window, then confirms it's a function—this is useful if you want to avoid false positives from variables with the same name in non-global scopes (though global functions will always be on window).
内容的提问来源于stack exchange,提问作者knave123

