-
-
Notifications
You must be signed in to change notification settings - Fork 737
/
index.js
59 lines (53 loc) · 1.55 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
'use strict'
const { PuppeteerExtraPlugin } = require('puppeteer-extra-plugin')
/**
* Anonymize the User-Agent on all pages.
*
* Supports dynamic replacing, so the Chrome version stays intact and recent.
*
* @param {Object} opts - Options
* @param {boolean} [opts.stripHeadless=true] - Replace `HeadlessChrome` with `Chrome`.
* @param {boolean} [opts.makeWindows=true] - Sets the platform to Windows 10, 64bit (most common).
* @param {Function} [opts.customFn=null] - A custom UA replacer function.
*
* @example
* const puppeteer = require('puppeteer-extra')
* puppeteer.use(require('puppeteer-extra-plugin-anonymize-ua')())
* // or
* puppeteer.use(require('puppeteer-extra-plugin-anonymize-ua')({
* customFn: (ua) => 'MyCoolAgent/' + ua.replace('Chrome', 'Beer')})
* )
* const browser = await puppeteer.launch()
*/
class Plugin extends PuppeteerExtraPlugin {
constructor (opts = {}) {
super(opts)
}
get name () {
return 'anonymize-ua'
}
get defaults () {
return {
stripHeadless: true,
makeWindows: true,
customFn: null
}
}
async onPageCreated (page) {
let ua = await page.browser().userAgent()
if (this.opts.stripHeadless) {
ua = ua.replace('HeadlessChrome/', 'Chrome/')
}
if (this.opts.makeWindows) {
ua = ua.replace(/\(([^)]+)\)/, '(Windows NT 10.0; Win64; x64)')
}
if (this.opts.customFn) {
ua = this.opts.customFn(ua)
}
this.debug('new ua', ua)
await page.setUserAgent(ua)
}
}
module.exports = function (pluginConfig) {
return new Plugin(pluginConfig)
}