const jsdom = require("jsdom"); const { JSDOM } = jsdom; const userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' const dom = newJSDOM(``, { url: "https://example.org/", referrer: "https://example.com/", userAgent: userAgent, }); window = dom.window console.log(window.navigator.userAgent)
以上代码输出的结果为: Mozilla/5.0 (darwin) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/24.0.0 在userAgent中有很明显的jsdom特征
再次尝试使用如下代码:
1 2 3 4 5 6 7
const jsdom = require("jsdom"); const { JSDOM } = jsdom; const dom = newJSDOM(); window = dom.window navigator = window.navigator navigator.userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' console.log(window.navigator.userAgent)
以上代码输出的结果仍然为: Mozilla/5.0 (darwin) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/24.0.0
jsdom正确设置userAgent
1 2 3 4 5 6 7 8 9 10 11 12 13
const jsdom = require("jsdom"); const { JSDOM } = jsdom; const userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' const resourceLoader = new jsdom.ResourceLoader({ userAgent: userAgent }); const dom = newJSDOM(``, { url: "https://example.org/", referrer: "https://example.com/", resources: resourceLoader, }); window = dom.window console.log(window.navigator.userAgent)
以上代码输出的结果为: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 通过以上方式则可以正常设置userAgent