https://www.npmjs.com/package/jsdom
npm install jsdom
var jsdom = require('jsdom')
var { JSDOM } = jsdom;
var dom = new JSDOM(``);
window = dom.window
document=window.document
navigator=window.navigator
//使用jq
const $ = require( "jquery" )( window );
new JSDOM('',{
url: 'https://example.org/', // window.location,document.URL
referrer: 'https://example.org/', // document.referrer
contentType: 'text/html',//内容类型
storageQuota: 10000000, //缓存大小
userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36',//userAgent请求头
includeNodeLocations: true,//允许查找dom位置,
runScripts: 'dangerously',//启用在页面内执行js,outside-only在外部执行js:window.eval()
cookieJar: new jsdom.CookieJar(),//cokkie
pretendToBeVisual:true,//因为JSDOM是无头的,该配置可假装是有头的,window.requestAnimationFrame() 、window.cancelAnimationFrame()
resources:new jsdom.ResourceLoader(option),//jsdom不会加载任何子资源(脚本、样式表、图像或iframe),该配置加载子资源
virtualConsole:new jsdom.VirtualConsole(),//虚拟控制台
beforeParse(window) {}
})
JSDOM.fromURL('https://www.baidu.com/', {
//同new JSDOM 中的option
}).then(dom => {
console.log(dom.serialize());
});
const document = JSDOM.fragment('Hellospan
Hi!
');
console.log(document.querySelector('p').innerHTML)
JSDOM.fromFile('stuff.html', {
//同new JSDOM 中的option
}).then(dom => {
console.log(dom.serialize());
});
var dom = new JSDOM('', { runScripts: "dangerously"})
const resources = new jsdom.ResourceLoader({
proxy: 'http://127.0.0.1:9001', //HTTP代理的地址。
strictSSL: false, //禁用SSL证书
userAgent: 'Mellblomenator/9000',//userAgent请求头
})
const dom = new JSDOM('', { resources });
const virtualConsole = new jsdom.VirtualConsole()
const dom = new JSDOM(``, { virtualConsole });
//监听事件
virtualConsole.on("error", () => { ... });
virtualConsole.on("warn", () => { ... });
virtualConsole.on("info", () => { ... });
virtualConsole.on("dir", () => { ... });
//重定向控制台到node
virtualConsole.sendTo(console,{
omitJSDOMErrors: true //jsdom报错信息
})
const cookieJar = new jsdom.VirtualConsole(store, options)
const dom = new JSDOM(``, { cookieJar });
const dom = new JSDOM('', {
includeNodeLocations: true
})
dom.window.onload = () => {
console.log(dom.nodeLocation(dom.window.document.body))
}