UNPKG

assertions-recorder

Version:

a module for publishing all dom and track events to the assertions recorder application

81 lines (68 loc) 2.21 kB
'use strict'; var _postmate = require('postmate'); var _postmate2 = _interopRequireDefault(_postmate); var _optimalSelect = require('optimal-select'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function attachWindowListeners(parent, eventsList) { eventsList.forEach(function (key) { window.addEventListener(key.slice(2), function (_ref) { var type = _ref.type, target = _ref.target; // Only emit this event for actual dom nodes if (target.nodeType === 1) { parent.emit('recorder-events', { type: type, path: (0, _optimalSelect.select)(target), data: target.value || '' }); } }); }); } /** * Instruments track calls to: * 1) Emit the dom event + associated data over the `recorder-events` "channel" to be * picked up in the parent frame * * 2) Send off the track event payload to the debug endpoint * * @param {*} parent * @param {*} ajs */ function instrumentAJS(parent, ajs) { var oldTrack = ajs.track; ajs.track = function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } parent.emit('recorder-events', { type: 'TRACK', path: 'track call', data: args[0] }); oldTrack.call.apply(oldTrack, [this].concat(args)); var createCORSRequest = function createCORSRequest(method, url) { var xhr = new XMLHttpRequest(); if ("withCredentials" in xhr) { xhr.open(method, url, true); } return xhr; }; var url = 'https://debug-api.segment.com/v1/track'; var method = 'POST'; var xhr = createCORSRequest(method, url); xhr.send(JSON.stringify({ event: args[0], properties: args[1], userId: ajs._user._getId() })); }; } new _postmate2.default.Model().then(function (parent) { attachWindowListeners(parent, Object.keys(window).filter(function (key) { return (/^on/i.test(key) ); }).filter(function (key) { return !/(pointer|mouse|wheel|transition|key|input|animation)/i.test(key); })), instrumentAJS(parent, analytics); });