1 |
|
2 |
|
3 |
|
4 |
|
5 | var html = '<!doctype html><html><head><meta charset="utf-8">' +
|
6 | '</head><body></body></html>'
|
7 |
|
8 | var blacklist = [
|
9 | 'ArrayBuffer', 'Int8Array', 'Uint8Array', 'Uint8ClampedArray',
|
10 | 'Int16Array', 'Uint16Array', 'Int32Array', 'Uint32Array', 'Float32Array',
|
11 | 'Float64Array', 'toString', 'constructor', 'console', 'setTimeout',
|
12 | 'clearTimeout', 'setInterval', 'clearInterval' ]
|
13 |
|
14 | module.exports = function globalJsdom (func) {
|
15 | if (typeof func === 'function') {
|
16 | try {
|
17 | var cleanup = globalize()
|
18 | return func()
|
19 | } finally {
|
20 | cleanup()
|
21 | }
|
22 | } else {
|
23 | return globalize()
|
24 | }
|
25 | }
|
26 |
|
27 | function globalize () {
|
28 |
|
29 | if (global.navigator &&
|
30 | global.navigator.userAgent &&
|
31 | global.navigator.userAgent.indexOf('Node.js') > -1 &&
|
32 | global.document &&
|
33 | typeof global.document.destroy === 'function') {
|
34 | return global.document.destroy
|
35 | }
|
36 |
|
37 | var jsdom = require('jsdom')
|
38 | var document = jsdom.jsdom(html)
|
39 | var window = document.defaultView
|
40 | var keys = []
|
41 |
|
42 | Object.keys(window).forEach(function (key) {
|
43 | if (blacklist.indexOf(key) !== -1) return
|
44 | keys.push(key)
|
45 | global[key] = window[key]
|
46 | })
|
47 |
|
48 | global.document = document
|
49 | global.window = window
|
50 | window.console = global.console
|
51 | document.destroy = cleanup
|
52 |
|
53 | function cleanup () {
|
54 | keys.forEach(function (key) { delete global[key] })
|
55 | }
|
56 |
|
57 | return cleanup
|
58 | }
|