Skip to content

Instantly share code, notes, and snippets.

@lincolnaleixo
Last active July 4, 2023 16:24
Show Gist options
  • Save lincolnaleixo/7ba13da90b4b08545bcb48ba8de7c92a to your computer and use it in GitHub Desktop.
Save lincolnaleixo/7ba13da90b4b08545bcb48ba8de7c92a to your computer and use it in GitHub Desktop.
undetectable puppeteer using headless
import puppeteer from 'puppeteer-extra'
import StealthPlugin from 'puppeteer-extra-plugin-stealth'
puppeteer.use(StealthPlugin())
const userAgent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'
const windowSize = [1920, 1080]
const userDataDir = './userDataDir'
const browserPath = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
const browserArgs = {
headless: 'new',
userDataDir,
args: ['--no-sandbox'],
executablePath: browserPath
}
const delay = ms => new Promise(_resolve => setTimeout(_resolve, ms))
const browser = await puppeteer.launch(browserArgs)
const pages = await browser.pages()
const page = pages[0]
await page.setUserAgent(userAgent)
// Enable request interception
await page.setRequestInterception(true)
// Set up dialog event listener
page.on('dialog', async dialog => {
console.log(`Alert dialog message: ${dialog.message()}`)
await delay(1000)
await dialog.dismiss()
})
// If the url ends with .png or .jpg, return a valid response
page.on('request', interceptedRequest => {
if (interceptedRequest.url()
.endsWith('.png') || interceptedRequest.url()
.endsWith('.jpg')) {
interceptedRequest.respond({
status: 200,
contentType: 'image/png',
body: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P//PwAFhAJ/wlseKgAAAABJRU5ErkJggg==', 'base64')
})
} else {
interceptedRequest.continue()
}
})
await page.setViewport({ width: windowSize[0], height: windowSize[1] })
await page.goto('https://infosimples.github.io/detect-headless/')
// Create a random offset for mouse movement
const offset = Math.random() * 10
// Make the mouse move in a small circle
for (let i = 0; i < 100; i++) {
const x = windowSize[0] / 2 + offset * Math.cos(2 * Math.PI * i / 100)
const y = windowSize[1] / 2 + offset * Math.sin(2 * Math.PI * i / 100)
await page.mouse.move(x, y)
}
await page.screenshot({ path: 'screenshot.png' })
await browser.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment