本文主要是介绍nodejs之jsdom插件,运行浏览器环境,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
https://www.npmjs.com/package/jsdom
一、安装依赖
npm install jsdom
二、用法
var jsdom = require('jsdom')
var { JSDOM } = jsdom;
var dom = new JSDOM(`<!DOCTYPE html><html lang="cn"><head></head><body></body></html>`);
window = dom.window
document=window.document
navigator=window.navigator
//使用jq
const $ = require( "jquery" )( window );
三、方法
- new JSDOM(domStr,option) 实例化一个dom环境
new JSDOM('',{url: 'https://example.org/', // window.location,document.URLreferrer: 'https://example.org/', // document.referrercontentType: '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(),//cokkiepretendToBeVisual:true,//因为JSDOM是无头的,该配置可假装是有头的,window.requestAnimationFrame() 、window.cancelAnimationFrame()resources:new jsdom.ResourceLoader(option),//jsdom不会加载任何子资源(脚本、样式表、图像或iframe),该配置加载子资源virtualConsole:new jsdom.VirtualConsole(),//虚拟控制台beforeParse(window) {} })
- JSDOM.fromURL() 通过url 实例化dom环境
JSDOM.fromURL('https://www.baidu.com/', { //同new JSDOM 中的option }).then(dom => {console.log(dom.serialize()); });
- JSDOM.fragment()通过字符串创建dom
const document = JSDOM.fragment('<p>Hello<span>span</span></p><p><strong>Hi!</strong></p>');console.log(document.querySelector('p').innerHTML)
- JSDOM.fromFile() 通过文件实例化dom环境
JSDOM.fromFile('stuff.html', {//同new JSDOM 中的option }).then(dom => {console.log(dom.serialize()); });
- 页面内执行js:runScripts
var dom = new JSDOM('<script>console.log(1)</script>', { runScripts: "dangerously"})
- new jsdom.ResourceLoader(option) 加载子资源
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 });
- new jsdom.VirtualConsole() 虚拟控制台
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报错信息 })
- new jsdom.CookieJar() cookie
const cookieJar = new jsdom.VirtualConsole(store, options) const dom = new JSDOM(``, { cookieJar });
- dom.serialize() 获取序列化dom
- dom.nodeLocation(bodyEl) 查找位置
const dom = new JSDOM('<body><p></p></body>', {includeNodeLocations: true })dom.window.onload = () => {console.log(dom.nodeLocation(dom.window.document.body)) }
- dom.window window对象
- document document对象
- window.navigator navigator对象
这篇关于nodejs之jsdom插件,运行浏览器环境的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!