assertions-recorder
Version:
a module for publishing all dom and track events to the assertions recorder application
69 lines (61 loc) • 1.72 kB
JavaScript
import Postmate from 'postmate'
import { select } from 'optimal-select'
function attachWindowListeners(parent, eventsList) {
eventsList.forEach(key => {
window.addEventListener(key.slice(2), ({ type, target }) => {
// Only emit this event for actual dom nodes
if (target.nodeType === 1) {
parent.emit('recorder-events', {
type,
path: 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(...args) {
parent.emit('recorder-events', {
type: 'TRACK',
path: 'track call',
data: args[0]
});
oldTrack.call(this, ...args);
var createCORSRequest = function(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 Postmate.Model().then(parent => {
attachWindowListeners(
parent,
Object.keys(window)
.filter(key => /^on/i.test(key))
.filter(key => !/(pointer|mouse|wheel|transition|key|input|animation)/i.test(key))
),
instrumentAJS(parent, analytics)
});