@shawwn/

sweetiekit-dom

Nodejs

Browser DOM in node

fork
loading
Files
  • index.js
  • package-lock.json
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Click the run button, up there ---^

// sweetiekit-dom
// http://github.com/sweetiebird/sweetiekit-dom
// 
// The sweetiekit-dom package provides a full
// browser API in pure JS: `window`, `document`,
// `navigator`, etc.
//
// Why is sweetiekit-dom different from projects like jsdom?
// https://www.npmjs.com/package/jsdom
//
// jsdom is a great DOM implementation, but it's
// not a complete browser implementation.
//
// Suppose you have a project that uses webpack hot
// reloading. Normally, you would run `yarn start`
// to start up webpack's dev server, then you'd
// open http://localhost:8080 in Chrome or FireFox.
// Whenever you make changes to your project,
// you'll see that change happen in your browser.
//
// Using sweetiekit-dom, you can do the same thing
// in NodeJS: simply load http://localhost:8080 and
// sweetiekit-dom will take care of maintaining a
// persistent websocket connection, reloading the
// page when hot patching fails, etc.
//
// In short, the behavior of sweetiekit-dom is
// identical to Chrome and Firefox for any
// arbitrary URL. If you notice a difference,
// please file an issue:
// https://github.com/sweetiebird/sweetiekit-dom/issues
//
// Credits
//
// sweetiekit-dom originated from Exokit, a mixed
// reality browser engine in JS: https://exokit.org
//
// Almost all of the work was done by Avaer Kazmer
// aka @modulesio: http://github.com/modulesio
//
// Demo
//
// This demo loads the front page of Hacker News
// and prints the top 30 stories.  The stories are
// extracted using nothing but the standard DOM
// interface defined by the HTML spec.
//
// To run this yourself:
// 1. $ npm install sweetiekit-dom
// 2. save this file to index.js
// 3. $ node index.js

SweetieKitDOM = require('sweetiekit-dom');

hn = async function hn() {
  // 1. load HN
  window = await SweetieKitDOM.load('https://news.ycombinator.com')

  // 2. make document, navigator, etc available globally
  // (this is mostly a REPL convenience)
  Object.assign(global, window);

  // 3. extract front page stories
  const stories = document.getElementsByClassName('athing');

  // 4. print headlines
  for (let story of stories) {
    console.log(story.textContent.trim());
  }

  // 5. Use the REPL on the right -->
  // Try to do anything you'd normally do 
  // in a Chrome or Firefox REPL, e.g.
  // console.log(document.body)
  return stories;
};

console.log("Loading https://news.ycombinator.com...");
hn()
node v10.16.0