版博士V2.0程序
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1 год назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. ![Happy DOM Logo](https://github.com/capricorn86/happy-dom/raw/master/docs/happy-dom-logo.jpg)
  2. # About
  3. [Happy DOM](https://github.com/capricorn86/happy-dom) is a JavaScript implementation of a web browser without its graphical user interface. It includes many web standards from WHATWG [DOM](https://dom.spec.whatwg.org/) and [HTML](https://html.spec.whatwg.org/multipage/).
  4. The goal of [Happy DOM](https://github.com/capricorn86/happy-dom) is to emulate enough of a web browser to be useful for testing, scraping web sites and server-side rendering.
  5. [Happy DOM](https://github.com/capricorn86/happy-dom) focuses heavily on performance and can be used as an alternative to [JSDOM](https://github.com/jsdom/jsdom).
  6. ### DOM Features
  7. - Custom Elements (Web Components)
  8. - Shadow Root (Shadow DOM)
  9. - Declarative Shadow DOM
  10. - Mutation Observer
  11. - Tree Walker
  12. - Fetch
  13. And much more..
  14. ### Works With
  15. - [Google LitHTML](https://lit-html.polymer-project.org)
  16. - [Google LitElement](https://lit-element.polymer-project.org)
  17. - [React](https://reactjs.org)
  18. - [Angular](https://angular.io/)
  19. - [Vue](https://vuejs.org/)
  20. # Installation
  21. ```bash
  22. npm install happy-dom
  23. ```
  24. # Usage
  25. ## Basic Usage
  26. A simple example of how you can use Happy DOM.
  27. ```javascript
  28. import { Window } from 'happy-dom';
  29. const window = new Window();
  30. const document = window.document;
  31. document.body.innerHTML = '<div class="container"></div>';
  32. const container = document.querySelector('.container');
  33. const button = document.createElement('button');
  34. container.appendChild(button);
  35. // Outputs "<div class="container"><button></button></div>"
  36. console.log(document.body.innerHTML);
  37. ```
  38. ## VM Context
  39. The default Window class is a [VM context](https://nodejs.org/api/vm.html#vm_vm_createcontext_sandbox_options). A [VM context](https://nodejs.org/api/vm.html#vm_vm_createcontext_sandbox_options) will execute JavaScript code scoped within the context where the Window instance will be the global object.
  40. ```javascript
  41. import { Window } from 'happy-dom';
  42. const window = new Window({
  43. innerWidth: 1024,
  44. innerHeight: 768,
  45. url: 'http://localhost:8080'
  46. });
  47. const document = window.document;
  48. document.write(`
  49. <html>
  50. <head>
  51. <title>Test page</title>
  52. </head>
  53. <body>
  54. <div class="container">
  55. <!–– Content will be added here -->
  56. </div>
  57. <script>
  58. const element = document.createElement('div');
  59. const container = document.querySelector('.container');
  60. element.innerHTML = 'Test';
  61. container.appendChild(element);
  62. </script>
  63. </body>
  64. </html>
  65. `);
  66. // Will output "Test"
  67. console.log(document.querySelector('.container div').innerHTML);
  68. ```
  69. ## Global Context
  70. Happy DOM exports a class called GlobalWindow, which can be used to run Happy DOM in the global context instead of the default behaviour of running in a [VM context](https://nodejs.org/api/vm.html#vm_vm_createcontext_sandbox_options).
  71. ```javascript
  72. import { Window, GlobalWindow } from 'happy-dom';
  73. const vmWindow = new Window();
  74. const globalWindow = new GlobalWindow();
  75. // Will output "false"
  76. console.log(vmWindow.Array === global.Array);
  77. // Will output "true"
  78. console.log(globalWindow.Array === global.Array);
  79. globalWindow.eval('global.test = 1');
  80. // Will output "1"
  81. console.log(global.test);
  82. ```
  83. ## Server-Side Rendering of Web Components
  84. The example below will show you how to setup a Node [VM context](https://nodejs.org/api/vm.html#vm_vm_createcontext_sandbox_options) to render a page with custom elements (web components) in Happy DOM. We can then use a new web feature called [Declarative Shadow DOM](https://chromestatus.com/feature/5191745052606464) to include the shadow roots in the HTML output.
  85. [Declarative Shadow DOM](https://chromestatus.com/feature/5191745052606464) is only supported by Chromium based browsers. Unsupported browsers should safely fallback to being rendered using Javascript.
  86. ```javascript
  87. import { Window } from 'happy-dom';
  88. const window = new Window({
  89. innerWidth: 1024,
  90. innerHeight: 768,
  91. url: 'http://localhost:8080'
  92. });
  93. const document = window.document;
  94. document.write(`
  95. <html>
  96. <head>
  97. <title>Test page</title>
  98. </head>
  99. <body>
  100. <div>
  101. <my-custom-element>
  102. <span>Slotted content</span>
  103. </my-custom-element>
  104. </div>
  105. <script>
  106. class MyCustomElement extends HTMLElement {
  107. constructor() {
  108. super();
  109. this.attachShadow({ mode: 'open' });
  110. }
  111. connectedCallback() {
  112. this.shadowRoot.innerHTML = \`
  113. <style>
  114. :host {
  115. display: inline-block;
  116. background: red;
  117. }
  118. </style>
  119. <div><slot></slot></div>
  120. \`;
  121. }
  122. }
  123. customElements.define('my-custom-element', MyCustomElement);
  124. </script>
  125. </body>
  126. </html>
  127. `);
  128. /*
  129. Will output:
  130. <my-custom-element>
  131. <span>Slotted content</span>
  132. <template shadowroot="open">
  133. <style>
  134. :host {
  135. display: inline-block;
  136. background: red;
  137. }
  138. </style>
  139. <div><slot></slot></div>
  140. </template>
  141. </my-custom-element>
  142. */
  143. console.log(document.body.querySelector('div').getInnerHTML({ includeShadowRoots: true }));
  144. ```
  145. ## Additional Features
  146. **whenAsyncComplete()**
  147. Returns a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that is resolved when all async tasks has been completed.
  148. ```javascript
  149. window.happyDOM.whenAsyncComplete().then(() => {
  150. // Do something when all async tasks are completed.
  151. });
  152. ```
  153. **cancelAsync()**
  154. This method will cancel all running async tasks.
  155. ```javascript
  156. window.setTimeout(() => {
  157. // This timeout will be canceled
  158. });
  159. window.happyDOM.cancelAsync();
  160. ```
  161. **setInnerWidth()**
  162. Sets the property `window.innerWidth` and dispatches a "resize" event.
  163. ```javascript
  164. window.happyDOM.setInnerWidth(1920);
  165. ```
  166. **setInnerHeight()**
  167. Sets the property `window.innerHeight` and dispatches a "resize" event.
  168. ```javascript
  169. window.happyDOM.setInnerHeight(1080);
  170. ```
  171. **setURL()**
  172. Sets the property `window.location.href`.
  173. ```javascript
  174. window.happyDOM.setURL('https://localhost:3000');
  175. ```
  176. ## Settings
  177. Settings can be sent to the constructor or by setting them on the "window.happyDOM.settings" property.
  178. Set by constructor:
  179. ```javascript
  180. const window = new Window({
  181. innerWidth: 1920,
  182. innerHeight: 1080,
  183. url: 'https://localhost:8080',
  184. settings: {
  185. disableJavaScriptFileLoading: true,
  186. disableJavaScriptEvaluation: true,
  187. disableCSSFileLoading: true,
  188. disableIframePageLoading: true,
  189. enableFileSystemHttpRequests: true
  190. }
  191. });
  192. ```
  193. Set by property:
  194. ```javascript
  195. const window = new Window();
  196. window.happyDOM.settings.disableJavaScriptFileLoading = true;
  197. window.happyDOM.settings.disableJavaScriptEvaluation = true;
  198. window.happyDOM.settings.disableCSSFileLoading = true;
  199. window.happyDOM.settings.disableIframePageLoading = true;
  200. window.happyDOM.settings.enableFileSystemHttpRequests = true;
  201. ```
  202. **disableJavaScriptFileLoading**
  203. Set it to "true" to disable JavaScript file loading. Defaults to "false".
  204. **disableJavaScriptEvaluation**
  205. Set it to "true" to completely disable JavaScript evaluation. Defaults to "false".
  206. **disableCSSFileLoading**
  207. Set it to "true" to disable CSS file loading in HTMLLinkElement. Defaults to "false".
  208. **disableIframePageLoading**
  209. Set it to "true" to disable page loading in HTMLIFrameElement. Defaults to "false".
  210. **enableFileSystemHttpRequests**
  211. Set it to "true" to enable file system HTTP requests using XMLHttpRequest. Defaults to "false".
  212. # Performance
  213. | Operation | JSDOM | Happy DOM |
  214. | ------------------------------------ | ------- | --------- |
  215. | Import / Require | 333 ms | 45 ms |
  216. | Parse HTML | 256 ms | 26 ms |
  217. | Serialize HTML | 65 ms | 8 ms |
  218. | Render custom element | 214 ms | 19 ms |
  219. | querySelectorAll('tagname') | 4.9 ms | 0.7 ms |
  220. | querySelectorAll('.class') | 6.4 ms | 3.7 ms |
  221. | querySelectorAll('[attribute]') | 4.0 ms | 1.7 ms |
  222. | querySelectorAll('[class~="name"]') | 5.5 ms | 2.9 ms |
  223. | querySelectorAll(':nth-child(2n+1)') | 10.4 ms | 3.8 ms |
  224. [See how the test was done here](https://github.com/capricorn86/happy-dom-performance-test)
  225. # Jest
  226. Happy DOM provide with a package called [@happy-dom/jest-environment](https://github.com/capricorn86/happy-dom/tree/master/packages/jest-environment) that makes it possible to use Happy DOM with [Jest](https://jestjs.io/).
  227. # Global Registration
  228. Happy DOM provide with a package called [@happy-dom/global-registrator](https://github.com/capricorn86/happy-dom/tree/master/packages/global-registrator) that can register Happy DOM globally. It makes it possible to use Happy DOM for testing in a Node environment.
  229. # Sponsors
  230. [<img alt="RTVision" width="120px" src="https://avatars.githubusercontent.com/u/8292810?s=200&v=4" />](https://rtvision.com)