Skip to content

Instantly share code, notes, and snippets.

@shawwn
Last active June 28, 2019 03:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shawwn/016ea51710f5624062d21a366d0c4f5f to your computer and use it in GitHub Desktop.
Save shawwn/016ea51710f5624062d21a366d0c4f5f to your computer and use it in GitHub Desktop.
sweetiekit-dom demo
// 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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment