browser.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. var ws = require('websocket-stream');
  2. var through = require('through2');
  3. // create connection to websocket server
  4. var stream = ws('ws://localhost:8001');
  5. stream.on('error', function(err){
  6. // console.log(err);
  7. });
  8. var domstream = require('domnode-dom');
  9. var hello = {
  10. "source": "browser",
  11. "id": new Date().getTime(),
  12. "url": window.location.href
  13. };
  14. stream.write(new Buffer(JSON.stringify(hello)))
  15. stream.on('data', function(x) {
  16. // console.log('data from server', x.toString());
  17. var data = JSON.parse(x.toString());
  18. var selector = data.selector;
  19. // if there is no data, assume its a request to bind a new event listerer from bpipe
  20. if (typeof data.data === "undefined") {
  21. var inputElement = document.querySelectorAll(selector)[0];
  22. var inputStream = domstream.createEventStream(inputElement, data.event);
  23. // console.log('mapping new element', inputElement, selector)
  24. inputStream.pipe(through(function(chunk, enc, cb){
  25. var data = {
  26. "selector": selector,
  27. "data": chunk.toString(),
  28. "source": "browser",
  29. "url": window.location.href
  30. };
  31. cb(null, JSON.stringify(data));
  32. }))
  33. .pipe(stream);
  34. } else {
  35. // data incoming from bpipe, send it to the browser
  36. var outputElement = document.querySelectorAll(selector)[0];
  37. var outputStream = domstream.createWriteStream(outputElement, 'text/plain');
  38. //console.log('incoming data from bpipe', data, outputElement);
  39. outputStream.write(data.data);
  40. }
  41. });