source: trunk/autoquest-htmlmonitor/src/main/js/autoquest-htmlmonitor.js @ 1654

Last change on this file since 1654 was 1248, checked in by pharms, 11 years ago
  • added tracing of key downs on tab key
File size: 36.4 KB
RevLine 
[927]1//   Copyright 2012 Georg-August-Universität Göttingen, Germany
2//
3//   Licensed under the Apache License, Version 2.0 (the "License");
4//   you may not use this file except in compliance with the License.
5//   You may obtain a copy of the License at
6//
7//       http://www.apache.org/licenses/LICENSE-2.0
8//
9//   Unless required by applicable law or agreed to in writing, software
10//   distributed under the License is distributed on an "AS IS" BASIS,
11//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//   See the License for the specific language governing permissions and
13//   limitations under the License.
14
[858]15/**
16 * AutoQUEST - HTML Monitor
17 *
18 * Description: This script records the interactions done by an user on an
19 * HTML-Website and sends them to a server. It does not register actions on
20 * Flash, Java, or other special inputs. This script is tested on Firefox
21 * 15.0.1.
22 *
23 * To insert it on your HTML-side, you need to write <script
24 * language="JavaScript" type="text/javascript" src="autoquest-htmlmonitor.js"></script> in the
25 * head and change the src-attribute to the location, you have chosen for this
26 * script.
27 *
28 * To change the recorded events, edit the action config array. If you want to change
29 * the server where the data is send to, rewrite the destination variable. The
30 * records are send to the server, JSON-formatted, if there are 10 inputs or the
31 * user changes/closes the site.
32 *
33 * Authors: Simon Leidenbach, Simon Reuss, Patrick Harms
34 *
35 * Version: 0.1
36 */
37
38/**
39 * the server to send the recorded data to
40 */
[879]41var autoquestDestination;
[858]42
43/**
[881]44 * an ID that is more or less unique for the client
45 */
46var autoquestClientId;
47
48/**
[858]49 * the maximum number of recorded events to be put into one package sent to the server
50 */
[879]51var autoquestPackageSize = 10;
[858]52
53/**
54 * this variable defines the tags for which event handling shall be added, as well as the
55 * event handling action to be monitored
56 */
[879]57var autoquestActionConfig = [
[944]58    { "tag": "a", "actions": [ "onclick",
59                               "onfocus" ] },
60    //{ "tag": "abbr", "actions": [  ] },
61    //{ "tag": "address", "actions": [  ] },
62    //{ "tag": "applet", "actions": [  ] },
63    { "tag": "area", "actions": [ "onclick",
64                                  "onfocus" ] },
65    //{ "tag": "article", "actions": [  ] },
66    //{ "tag": "aside", "actions": [  ] },
67    { "tag": "audio", "actions": [ "onplaying",
68                                   "onpause",
69                                   "ontimeupdate" ] },
70    { "tag": "b", "actions": [ "onclick" ] },
71    //{ "tag": "bdi", "actions": [  ] },
72    //{ "tag": "bdo", "actions": [  ] },
73    //{ "tag": "blockquote", "actions": [  ] },
[1073]74    { "tag": "body", "actions": [ "onclick",
[1248]75                                  "onkeydown",
[944]76                                  "onpagehide",
77                                  "onpageshow",
[1073]78                                  "onscroll",
[944]79                                  "onundo" ] },
80    { "tag": "button", "actions": [ "onclick",
81                                    "onfocus" ] },
82    { "tag": "canvas", "actions": [ "onclick" ] },
83    //{ "tag": "caption", "actions": [  ] },
84    { "tag": "cite", "actions": [ "onclick" ] },
85    { "tag": "code", "actions": [ "onclick" ] },
86    //{ "tag": "col", "actions": [  ] },
87    //{ "tag": "colgroup", "actions": [  ] },
88    { "tag": "command", "actions": [ "onclick",
89                                     "onfocus" ] },
90    //{ "tag": "datalist", "actions": [  ] },
91    { "tag": "dd", "actions": [ "onclick" ] },
92    { "tag": "del", "actions": [ "onclick" ] },
93    //{ "tag": "details", "actions": [  ] },
94    { "tag": "dfn", "actions": [ "onclick" ] },
[1247]95    { "tag": "div", "actions": [ "onclick",
96                                 "onscroll" ] },
[944]97    //{ "tag": "dl", "actions": [  ] },
98    { "tag": "dt", "actions": [ "onclick" ] },
99    { "tag": "em", "actions": [ "onclick" ] },
100    { "tag": "embed", "actions": [ "onclick" ] },
101    //{ "tag": "fieldset", "actions": [  ] },
102    //{ "tag": "figcaption", "actions": [  ] },
103    //{ "tag": "figure", "actions": [  ] },
104    //{ "tag": "footer", "actions": [  ] },
[999]105    { "tag": "form", "actions": [ "onreset",
106                                  "onsubmit" ] },
[944]107    //{ "tag": "header", "actions": [  ] },
108    //{ "tag": "hgroup", "actions": [  ] },
109    { "tag": "h1", "actions": [ "onclick" ] },
110    { "tag": "h2", "actions": [ "onclick" ] },
111    { "tag": "h3", "actions": [ "onclick" ] },
112    { "tag": "h4", "actions": [ "onclick" ] },
113    { "tag": "h5", "actions": [ "onclick" ] },
114    { "tag": "h6", "actions": [ "onclick" ] },
115    //{ "tag": "hr", "actions": [  ] },
116    { "tag": "i", "actions": [ "onclick" ] },
117    //{ "tag": "iframe", "actions": [  ] },
[999]118    { "tag": "img", "actions": [ "onabort",
119                                 "onclick" ] },
[1247]120    { "tag": "input_button", "actions": [ "onclick",
121                                          "onfocus" ] },
122    { "tag": "input_checkbox", "actions": [ "onchange",
123                                            "onclick",
124                                            "onfocus" ] },
125    { "tag": "input_color", "actions": [ "onchange",
126                                         "onclick",
127                                         "onfocus",
128                                         "onselect" ] },
129    { "tag": "input_date", "actions": [ "onchange",
130                                        "onclick",
[999]131                                        "onfocus",
132                                        "onselect" ] },
[1247]133    { "tag": "input_datetime", "actions": [ "onchange",
134                                            "onclick",
135                                            "onfocus",
136                                            "onselect" ] },
137    { "tag": "input_datetime-local", "actions": [ "onchange",
138                                                  "onclick",
139                                                  "onfocus",
140                                                  "onselect" ] },
141    { "tag": "input_email", "actions": [ "onchange",
142                                         "onclick",
143                                         "onfocus",
144                                         "onselect" ] },
145    { "tag": "input_file", "actions": [ "onchange",
146                                        "onclick",
147                                        "onfocus",
148                                        "onselect" ] },
149    { "tag": "input_image", "actions": [ "onclick",
150                                         "onfocus" ] },
151    { "tag": "input_month", "actions": [ "onchange",
152                                         "onclick",
153                                         "onfocus",
154                                         "onselect" ] },
155    { "tag": "input_number", "actions": [ "onchange",
156                                          "onclick",
157                                          "onfocus",
158                                          "onselect" ] },
[992]159    { "tag": "input_password", "actions": [ "onchange",
160                                            "onclick",
161                                            "onfocus" ] },
162    { "tag": "input_radio", "actions": [ "onchange",
163                                         "onclick",
164                                         "onfocus" ] },
[1247]165    { "tag": "input_range", "actions": [ "onchange",
166                                         "onclick",
167                                         "onfocus",
168                                         "onselect" ] },
[992]169    { "tag": "input_reset", "actions": [ "onclick",
170                                         "onfocus" ] },
[1247]171    { "tag": "input_search", "actions": [ "onchange",
172                                          "onclick",
173                                          "onfocus",
174                                          "onselect" ] },
175    { "tag": "input_submit", "actions": [ "onclick",
[992]176                                          "onfocus" ] },
[1247]177    { "tag": "input_tel", "actions": [ "onchange",
178                                       "onclick",
179                                       "onfocus",
180                                       "onselect" ] },
181    { "tag": "input_text", "actions": [ "onchange",
182                                        "onclick",
183                                        "onfocus",
184                                        "onselect" ] },
185    { "tag": "input_time", "actions": [ "onchange",
186                                        "onclick",
187                                        "onfocus",
188                                        "onselect" ] },
189    { "tag": "input_url", "actions": [ "onchange",
190                                       "onclick",
191                                       "onfocus",
192                                       "onselect" ] },
193    { "tag": "input_week", "actions": [ "onchange",
194                                        "onclick",
195                                        "onfocus",
196                                        "onselect" ] },
[944]197    { "tag": "input", "actions": [ "onchange",
[1247]198                                   "onclick",
[944]199                                   "onfocus" ] },
200    { "tag": "ins", "actions": [ "onclick" ] },
201    { "tag": "kbd", "actions": [ "onclick" ] },
202    { "tag": "keygen", "actions": [ "onchange",
203                                    "onfocus" ] },
204    //{ "tag": "label", "actions": [  ] },
205    //{ "tag": "legend", "actions": [  ] },
206    { "tag": "li", "actions": [ "onclick" ] },
207    //{ "tag": "map", "actions": [  ] },
208    { "tag": "mark", "actions": [ "onclick" ] },
209    { "tag": "menu", "actions": [ "onclick" ] },
210    { "tag": "meter", "actions": [ "onclick" ] },
211    //{ "tag": "nav", "actions": [  ] },
212    //{ "tag": "noscript", "actions": [  ] },
213    { "tag": "object", "actions": [ "onclick" ] },
214    //{ "tag": "ol", "actions": [  ] },
215    //{ "tag": "optgroup", "actions": [  ] },
216    //{ "tag": "option", "actions": [  ] },
217    { "tag": "output", "actions": [ "onclick" ] },
218    { "tag": "p", "actions": [ "onclick" ] },
219    //{ "tag": "param", "actions": [  ] },
220    //{ "tag": "pre", "actions": [  ] },
221    { "tag": "progress", "actions": [ "onclick" ] },
222    { "tag": "q", "actions": [ "onclick" ] },
223    //{ "tag": "rp", "actions": [  ] },
224    //{ "tag": "rt", "actions": [  ] },
225    //{ "tag": "ruby", "actions": [  ] },
226    { "tag": "s", "actions": [ "onclick" ] },
227    { "tag": "samp", "actions": [ "onclick" ] },
228    //{ "tag": "section", "actions": [  ] },
229    { "tag": "select", "actions": [ "onchange",
230                                    "onfocus" ] },
231    { "tag": "small", "actions": [ "onclick" ] },
232    //{ "tag": "source", "actions": [  ] },
233    { "tag": "span", "actions": [ "onclick" ] },
234    { "tag": "strong", "actions": [ "onclick" ] },
235    //{ "tag": "sub", "actions": [  ] },
236    //{ "tag": "summary", "actions": [  ] },
237    //{ "tag": "sup", "actions": [  ] },
238    //{ "tag": "table", "actions": [  ] },
239    //{ "tag": "tbody", "actions": [  ] },
240    { "tag": "td", "actions": [ "onclick" ] },
241    { "tag": "textarea", "actions": [ "onchange",
[999]242                                      "onfocus",
243                                      "onselect" ] },
[944]244    //{ "tag": "tfoot", "actions": [  ] },
245    { "tag": "th", "actions": [ "onclick" ] },
246    //{ "tag": "thead", "actions": [  ] },
247    { "tag": "time", "actions": [ "onclick" ] },
248    //{ "tag": "tr", "actions": [  ] },
249    //{ "tag": "track", "actions": [  ] },
250    { "tag": "u", "actions": [ "onclick" ] },
251    //{ "tag": "ul", "actions": [  ] },
252    { "tag": "var", "actions": [ "onclick" ] },
253    { "tag": "video", "actions": [ "onplaying",
254                                   "onpause",
[1020]255                                   "ontimeupdate" ] }
[944]256    //{ "tag": "wbr", "actions": [  ] },
[858]257];
258
259/**
260 * a possibility to trace, what is going on
261 */
[879]262var autoquestDoLog = false;
[858]263
[869]264/**
[1020]265 * stores the structure of the GUI of the current page
266 */
267var autoquestGUIModel;
268
269/**
[869]270 * stores events, which were recorded but not sent to the server yet
271 */
[879]272var autoquestRecordedEvents = [];
[858]273
274/**
[999]275 * stores the interval for sending data of inactive browser windows
276 */
277var autoquestSendInterval;
278
279/**
[869]280 * automatically executed to initialize the event handling
[858]281 */
282(function() {
283    initEventHandling();
284}());
285
286
287/**
288 * initializes the event handling after the document is loaded completely
289 */
290function initEventHandling() {
291    if (document.body) {
292        if (document.readyState !== "complete") {
293            // if the document is not loaded yet, try to add further event handling later
294            setTimeout(initEventHandling, 200);
295        }
[999]296        else if (!autoquestSendInterval) {
[1021]297            log("adding event handling attributes");
298            determineDestination();
299            autoquestGUIModel =
300                addEventHandlingAndGetJSONRepresentation(document.documentElement, "");
301           
[1073]302            addDefaultEventHandling();
303           
[999]304            // recall sending data each 100 seconds to ensure, that for browser windows staying
305            // open the data will be send, as well.
306            autoquestSendInterval = setTimeout(sendRequest, 100000);
307        }
[858]308    }
309    else {
310        setTimeout(initEventHandling, 200);
311    }         
312}
313
314/**
[879]315 * traverses the DOM-structure of the HTML-site and determines the URL of this script. Based on
316 * this URL, it calculates the destination to which the traced interactions must be sent
317 */
318function determineDestination() {
319    var scriptElements = document.getElementsByTagName("script");
320    var i;
321    var index;
322   
323    for (i = 0; i < scriptElements.length; i++) {
324        if ((scriptElements[i].type === "text/javascript") && (scriptElements[i].src)) {
325            index = scriptElements[i].src.lastIndexOf("script/autoquest-htmlmonitor.js");
326            if (index > -1) {
327                autoquestDestination = scriptElements[i].src.substring(0, index - 1);
328                log("using destination " + autoquestDestination);
329            }
330        }
331    }
332}
333
334/**
335 * traverses the DOM-structure of the HTML-site and adds event handling attributes to each
[1020]336 * relevant node. Furthermore returns a JSON representation of the node including the children
[858]337 *
[869]338 * @param node       the node of the DOM structure that shall be adapted and whose children shall
339 *                   be traversed
340 * @param parentPath the path to the parent node of the provided node within the DOM-structure of
341 *                   the HTML-site
[858]342 */
[1020]343function addEventHandlingAndGetJSONRepresentation(node, parentPath) {
[944]344    var nodePath;
[858]345    var i;
[1020]346    var jsonRepresentation = null;
347    var childRepresentation;
348    var childRepresentations = null;
[858]349   
350    if (node.nodeType === Node.ELEMENT_NODE) {
[1020]351        jsonRepresentation = "{\"tagName\":\"" + getTagName(node) + "\",";
[944]352       
[1020]353        if ((node.id) && (node.id !== "")) {
[1069]354            jsonRepresentation += "\"htmlId\":\"" + node.id + "\"";
[1020]355        }
356        else {
357            jsonRepresentation += "\"index\":\"" + getNodeIndex(node) + "\"";
358        }
359       
360        addEventHandling(node, parentPath);
361       
362        if (node.childNodes.length > 0) {
363            nodePath = getNodePath(node, parentPath);
364           
365            for (i = 0; i < node.childNodes.length; i++) {
366                childRepresentation =
367                    addEventHandlingAndGetJSONRepresentation(node.childNodes[i], nodePath);
368               
369                if (childRepresentation) {
370                    if (!childRepresentations) {
371                        childRepresentations = childRepresentation;
[858]372                    }
373                    else {
[1020]374                        childRepresentations += "," + childRepresentation;
[858]375                    }
376                }
377            }
[1020]378
379            if (childRepresentations) {
380                jsonRepresentation += ",\"children\":[" + childRepresentations + "]";
381            }
[858]382        }
[944]383       
[1020]384        jsonRepresentation += "}";
385    }
386   
387    return jsonRepresentation;
388}
389
390/**
[1022]391 * adds event handling functionality to the provided node. Calls
392 * {@link #addEventHandlingWithJQuery(node,parentPath)} or
393 * {@link #addEventHandlingWithoutJQuery(node,parentPath)} depending on the fact if jQuery is
394 * available and must therefore be used, or not.
395 *
396 * @param node       the node of the DOM structure that shall be equipped with event handling
397 * @param parentPath the path to the parent node of the provided node within the DOM-structure of
398 *                   the HTML-site
[1020]399 */
400function addEventHandling(node, parentPath) {
401    if (typeof jQuery === 'undefined') {
402        addEventHandlingWithoutJQuery(node, parentPath);
403    }
404    else {
405        addEventHandlingWithJQuery(node, parentPath);
406    }
407}
408
409/**
[1022]410 * adds event handling functionality to the provided node using onxxx attributes
411 *
412 * @param node       the node of the DOM structure that shall be equipped with event handling
413 * @param parentPath the path to the parent node of the provided node within the DOM-structure of
414 *                   the HTML-site
[1020]415 */
416function addEventHandlingWithoutJQuery(node, parentPath) {
417    var nodePath = getNodePath(node, parentPath);
418    var tagName = getTagName(node);
419    var i;
420    var k;
421   
422    for (i = 0; i < autoquestActionConfig.length; i++) {
423        if (tagName === autoquestActionConfig[i].tag.toLowerCase()) {
424            for (k = 0; k < autoquestActionConfig[i].actions.length; k++) {
425                adaptEventHandlingAttribute(node, nodePath, autoquestActionConfig[i].actions[k]);
426            }
[944]427        }
[858]428    }
429}
430
431/**
[1022]432 * adds event handling functionality to the provided node using jQuery attributes. If the node
433 * already used onxxx attributes, these are extended instead of using jQuery.
434 *
435 * @param node       the node of the DOM structure that shall be equipped with event handling
436 * @param parentPath the path to the parent node of the provided node within the DOM-structure of
437 *                   the HTML-site
[1020]438 */
439function addEventHandlingWithJQuery(node, parentPath) {
440    var nodePath = getNodePath(node, parentPath);
441    var tagName = getTagName(node);
442    var action;
443    var i;
444    var k;
445   
446    for (i = 0; i < autoquestActionConfig.length; i++) {
447        if (tagName === autoquestActionConfig[i].tag.toLowerCase()) {
448            for (k = 0; k < autoquestActionConfig[i].actions.length; k++) {
449                action = autoquestActionConfig[i].actions[k];
450                if (jQuery(node).attr(action)) {
451                    // if there is an event handling attribute although jquery is present
452                    // edit this attribute accordingly
453                    adaptEventHandlingAttribute(node, nodePath, action);
454                }
455                else {
[1073]456                    registerEventHandler(node, nodePath, action);
[1020]457                }
458            }
459        }
460    }
461}
462
463/**
[1022]464 * adapts the event handling attributed provided by the action parameter so that it calls
[1073]465 * the {@link #handleEvent(node, action, path, event)} function in the case the event occurs.
[1022]466 * Either the method creates an appropriate onxxx attribute on the node if there is none, or it
467 * adds a call to the function as first thing called by the onxxx attribute.
468 *
469 * @param node     the node of the DOM structure that shall be equipped with event handling
[1073]470 * @param nodePath the path to the node within the DOM-structure of the HTML-site
[1022]471 * @param action   the event for which event handling shall be enabled
[1020]472 */
473function adaptEventHandlingAttribute(node, nodePath, action) {
474    var value = "handleEvent(this, '" + action + "', '" + nodePath + "', event);";
475    var oldValue;
476   
477    if (!node.getAttribute(action)) {
478        node.setAttribute(action, value);
479    }
480    else {
481        oldValue = node.getAttribute(action);
482        if (oldValue.indexOf(value) < 0) {
483            node.setAttribute(action, value + ' ' + oldValue);
484        }
485    }
486}
487
488/**
[1073]489 * registers an event handler using jQuery for the provided action on the given object so that it
490 * calls the {@link #handleJQueryEvent(event)} function in the case the event occurs.
491 *
492 * @param node     the node of the DOM structure that shall be equipped with event handling
493 * @param nodePath the path to the node within the DOM-structure of the HTML-site
494 * @param action   the event for which event handling shall be enabled
495 */
496function registerEventHandler(node, nodePath, action) {
497    var parameters = { action : action, path : nodePath};
[1247]498   
499    if ((action === "onscroll") && (node === document.body)) {
500        node = window;
501    }
502   
[1073]503    if (jQuery(node).on) {
504        jQuery(node).on(action.substring(2), parameters, handleJQueryEvent);
505    }
506    else {
507        jQuery(node).bind(action.substring(2), parameters, handleJQueryEvent);
508    }
509}
510
511/**
512 * adds default event handling functionality for receiving load, unload, and other document
513 * relevant events. The registration for events is done depending on the availability of jQuery.
514 * If jQuery is available and must therefore be used, then the registration is done on the window
515 * object. Otherwise, the appropriate attributes of the document's body tag are changed
516 */
517function addDefaultEventHandling() {
518    var body;
519
520    if (typeof jQuery === 'undefined') {
521        body = document.getElementsByTagName("body").item(0);
522        adaptEventHandlingAttribute(body, "/html[0]/body[0]", "onbeforeunload");
523        adaptEventHandlingAttribute(body, "/html[0]/body[0]", "onload");
524        adaptEventHandlingAttribute(body, "/html[0]/body[0]", "onunload");
525        //adaptEventHandlingAttribute(body, "/html[0]/body[0]", "onerror");
526    }
527    else {
528        registerEventHandler(window, "/html[0]/body[0]", "onbeforeunload");
529        registerEventHandler(window, "/html[0]/body[0]", "onload");
530        registerEventHandler(window, "/html[0]/body[0]", "onunload");
531        //registerEventHandler(body, "/html[0]/body[0]", "onerror");
532    }
533}
534
535/**
[869]536 * generates a path through the DOM-structure of the HTML-site depending on a node and the path
537 * to its parent node. The result is the parent path plus a path element for the provided node.
[944]538 * The first part of the path element generated for the node is the tag name returned by
539 * {@link #getTagName(node)}. If the node has an id, it becomes the second part of the path
540 * element. If the node does not have an id, the method calculates the index of the node within
541 * all children of the same type within the parent node. This index becomes then the second part
542 * of the path element generated for the node.
[858]543 *
[869]544 * @param node       the node of the DOM structure for which the path shall be created
545 * @param parentPath the path to the parent node of the provided node
546 *
547 * @returns a path in the DOM-structure of the HTML-site including the parent path an a path
548 *          element for the provided node
[858]549 */
550function getNodePath(node, parentPath) {
[1020]551    var nodePath = parentPath + "/" + getTagName(node);
[858]552   
553    if ((node.id) && (node.id !== "")) {
[1082]554        nodePath += "(htmlId=" + node.id + ")";
[858]555    }
556    else {
[1020]557        nodePath += "[" + getNodeIndex(node) + "]";
[858]558    }
559   
560    return nodePath;
561}
562
563/**
[1023]564 * called to handle events caused by the jQuery event handling mechanism. Forwards the event to
565 * {@link #handleEvent(node, eventName, nodePath, event)}
566 *
567 * @param the event to be handled
[1020]568 */
569function handleJQueryEvent(event) {
570    handleEvent(this, event.data.action, event.data.path, event);
571}
572
573/**
[869]574 * handles an event that happened on a node. This method is called by the event handling attributes
575 * of the nodes. These attributes are generated by the
576 * {@link #addEventHandlingAttributes(node,parentPath)} function. It creates a new Event object and
[944]577 * adds it to the list of <code>autoquestRecordedEvents</code>. If this list achieves the maximum
[879]578 * <code>autoquestPackageSize</code> the events in the list are sent to the server asynchronously
579 * through calling {@link #sendRequest()}.
[858]580 *
[944]581 * @param node      the node that fired the event
[869]582 * @param eventName the name of the event, e.g. onscroll
583 * @param nodePath  the path to the node in the HTML DOM on which the event occurred
584 * @param event     the HTML event that occured
[858]585 */
[944]586function handleEvent(node, eventName, nodePath, event) {
587    var eventType;
588    var eventObj = null;
589    var tagName;
[1244]590    var unmonitored;
[944]591
[879]592    if (!autoquestDestination) {
593        // do nothing if we have no destination to send data to
594        return;
595    }
596   
[944]597    log("handling event " + eventName + " on " + node);
[858]598   
[944]599    eventType = eventName.toLowerCase();
[1248]600   
601    // filter onkeydown events, which are not of interest
602    if ((eventType === "onkeydown") && (node === document.body)) {
603        // do not handle key downs on the body which are other than tabs (keycode 9)
604        if (event.keyCode !== 9) {
605            return;
606        }
607    }
[944]608
[1247]609    // check, if the preceeding event is more concrete, i.e. the new event to be handled is only
610    // a propagation through the DOM and needs, therefore, not be handled
[944]611    if (autoquestRecordedEvents.length > 0) {
612        eventObj = autoquestRecordedEvents[autoquestRecordedEvents.length - 1];
613
614        if ((eventObj.type === eventName) && (eventObj.nodePath.indexOf(nodePath) === 0)) {
615            // the event is of the same type.
616            if (eventObj.nodePath.length > nodePath.length) {
[1247]617                // the new event is the same event as the previous one, but fired for the parent
618                // GUI element of the previous event. This must not be handled. So ignore it
[944]619                log("discarding event " + eventName + " on " + node +
620                    " as it is already handled by a child");
621                return;
622            }
[1248]623            else if (eventType !== "onscroll") {
[944]624                // we have the same event on the same element. If it is an onscroll, we should
625                // reuse it. But it is not an onscroll. So we ignore the existing event.
626                eventObj = null;
627            }
628        }
629        else {
630            // the event is not of an equal type as the previous one. So we will not reuse it
631            eventObj = null;
632        }
633    }
[858]634   
[944]635    if (!eventObj) {
[1247]636        // we can not reuse the previous event. So create a new event and add it to the list
[858]637        eventObj = new Event(eventType, nodePath);
[944]638        log("storing event " + eventName);
639        autoquestRecordedEvents.push(eventObj);
[858]640    }
[944]641
642    // now add further event parameters
[858]643    if ((eventType === "onclick") || (eventType === "ondblclick")) {
644        eventObj.setClickCoordinates(getEventCoordinates(event));
645    }
646
[944]647    tagName = getTagName(node);
648   
[1247]649    // ensure to not monitor details for GUI elements marked as unmonitored
[1244]650    if (node.getAttribute && node.getAttribute("class")) {
651        unmonitored = node.getAttribute("class").indexOf("autoquest-unmonitored") >= 0;
652    }
653    else {
654        unmonitored = false;
655    }
656   
657    if (!unmonitored && ("input_password" !== tagName)) {
[1247]658        // add further parameters for GUI elements which are monitored and which are no password
659        // fields
[944]660        if ((eventType === "onkeypress") ||
661            (eventType === "onkeydown") ||
662            (eventType === "onkeyup"))
663        {
664            eventObj.setKey(event.keyCode);
665        }
[1020]666        else if (eventType === "onchange") {
[944]667            if ((tagName.indexOf("input") === 0) ||
668                (tagName === "textarea") ||
669                (tagName === "keygen"))
670            {
671                eventObj.setSelectedValue(node.value);
672            }
673            else if (tagName === "select") {
674                eventObj.setSelectedValue(node.options.item(node.options.selectedIndex));
675            }
676        }
[858]677    }
678   
679    if (eventType === "onscroll") {
[944]680        eventObj.setScrollPosition(getScrollCoordinates(node));
[858]681    }
682
[1247]683    // finally send the recorded data
[879]684    if (autoquestRecordedEvents.length >= autoquestPackageSize) {
685        log("initiating sending events");
[875]686        setTimeout(sendRequest, 100);
[858]687    }
[999]688    else if ((eventType === "onunload") || (eventType === "onbeforeunload")) {
[879]689        log("initiating sending events");
690        sendRequest();
691    }
[858]692
693}
694
695/**
[944]696 * determines a tag name of a node. If the node is an input element, the tag name includes the
697 * type of element. Otherwise the method simply returns the tag name.
698 *
699 * @param node the node for which the name must be determined
700 *
701 * @return the name as described
702 */
703function getTagName(node) {
704    var tagName = null;
705   
706    if (node.tagName) {
707        tagName = node.tagName.toLowerCase();
708        if ("input" === tagName) {
709            if (node.type && (node.type !== "")) {
710                tagName += "_" + node.type;
711            }
712            else {
713                tagName += "_text";
714            }
715        }
716    }
717
718    return tagName;
719}
720   
721/**
[1020]722 * determines the index of a node considering all nodes of the parent having the same name. If the
723 * node has no parent, the method returns index 0.
724 *
725 * @param node the node for which the index must be determined
726 *
727 * @return the index as described
728 */
729function getNodeIndex(node) {
730    var i;
731    var index = 0;
732   
733    if (node.parentNode) {
734        for (i = 0; i < node.parentNode.childNodes.length; i++) {
735            if (node.parentNode.childNodes[i].tagName === node.tagName) {
736                // if === also returns true if the nodes are not identical but only equal,
737                // this may fail.
738                if (node.parentNode.childNodes[i] === node) {
739                    break;
740                }
[1073]741                index++;
[1020]742            }
743        }
744       
745    }
746
747    return index;
748}
749   
750/**
[869]751 * sends the collected data to the server, named in the destination-variable. For this it generates
[879]752 * a JSON formatted message and uses Ajax and the <code>autoquestDestination</code> to send it to
753 * the server
[858]754 */
755function sendRequest() {
[1020]756    var eventList = autoquestRecordedEvents;
[858]757    var message;
758    var clientId;
759    var i = 0;
760    var request;
761   
[1020]762    if (eventList.length > 1) {
[879]763        log("creating message");
[858]764       
[944]765        // put the last event into the new list to allow for checks for reoccurence of the same
766        // event
767        autoquestRecordedEvents = [ eventList.pop() ];
768       
[858]769        message = "{\"message\":{\"clientInfos\":{";
770       
771        log("reading client id");
[881]772        clientId = getClientId();
[858]773        if ((clientId) && (clientId !== "")) {
774            message += "\"clientId\":\"" + clientId + "\",";
775        }
776       
777        log("adding other infos");
778        message += "\"userAgent\":\"" + navigator.userAgent + "\",";
779        message += "\"title\":\"" + document.title + "\",";
780        message += "\"url\":\"" + document.URL + "\"},";
781       
[1020]782        message += "\"guiModel\":" + autoquestGUIModel + ",";
[858]783       
784        message += "\"events\":[";
785       
786        for (i = 0; i < eventList.length; i++) {
787            if (i > 0) {
788                message += ",";
789            }
790            message += eventList[i].toJSON();
791        }
792       
793        message += "]}}";
794       
795        request = null;
796       
797        // Mozilla
798        if (window.XMLHttpRequest) {
799            request = new XMLHttpRequest();
800        }
801        // IE
802        else if (window.ActiveXObject) {
803            request = new ActiveXObject("Microsoft.XMLHTTP");
804        }
805       
[881]806        request.open("POST", autoquestDestination, false);
807        request.setRequestHeader("Content-Type", "application/json");
[858]808
809        log("sending " + message);
810        request.send(message);
811    }
812}
813
814/**
[944]815 * determines the scroll coordinates of the scrolled element
816 *
817 * @param node the element that was scrolled
818 *
819 * @returns the coordinates of the scrolling as an array with x and y coordinate
820 */
821function getScrollCoordinates(node) {
822    if (node.scrollLeft || node.scrollTop) {
823        return [node.scrollLeft, node.scrollTop];
824    }
825    else if ((node === window) && window.pageYOffset) {
826        return [window.pageXOffset, window.pageYOffset];
827    }
828    else if ((node == document) || (node == document.body) || (node == document.documentElement)) {
829        if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
830            return [document.body.scrollLeft, document.body.scrollTop];
831        }
832        else if (document.documentElement &&
833                 (document.documentElement.scrollLeft || document.documentElement.scrollTop))
834        {
835            return [document.documentElement.scrollLeft, document.documentElement.scrollTop];
836        }
837    }
838
839    return [-1, -1];
840}
841
842/**
[869]843 * determines the coordinates of an onclick or ondblclick event. If the coordinates to not come
844 * with the provided event, they are determined based on the surrounding object
845 *
846 * @param event the event to extract the coordinates of
847 *
848 * @returns the coordinates of the event as an array with x and y coordinate
[858]849 */
850function getEventCoordinates(event) {
851    if (event.layerX) {
852        return [event.layerX, event.layerY];
853    }
854    else if (event.offsetX) {
855        return [event.offsetX, event.offsetY];
856    }
857
858    var obj = event.target || event.srcElement;
859    var objOffset = getPageOffset(obj);
860
861    return [(event.clientX - objOffset[0]), (event.clientY - objOffset[1])];
862}
863
864/**
865 * determines the page offset of an object using the parent objects offset
866 */
867function getPageOffset(object) {
868    var top = 0;
869    var left = 0;
870    var obj = object;
871
872    while (obj.offsetParent) {
873        left += obj.offsetLeft;
874        top += obj.offsetTop;
875        obj = obj.offsetParent;
876    }
877
878    return [left, top];
879}
880
881/**
[881]882 * generates a client id based on several information retrieved from the environment. The client
883 * id is not always unique
[858]884 *
[881]885 * @returns the client id
[858]886 */
[881]887function getClientId() {
888    var clientIdStr;
889    var clientId;
890    var i = 0;
[858]891   
[881]892    if (!autoquestClientId) {
893        // create something like a more or less unique checksum.
894        clientIdStr =
895            navigator.appCodeName + navigator.appName + navigator.appVersion +
896            navigator.cookieEnabled + navigator.language + navigator.platform +
897            navigator.userAgent + navigator.javaEnabled() + window.location.protocol +
898            window.location.host + new Date().getTimezoneOffset();
[858]899
[881]900        clientId = clientIdStr.length;
901
902        for (i = 0; i < clientIdStr.length; i++) {
903            clientId += clientIdStr.charCodeAt(i);
904        }
[858]905       
[881]906        autoquestClientId = clientId;
[858]907    }
908
[881]909    return autoquestClientId;
[858]910}
911
912/**
[869]913 * performs a simple logging by adding a specific div to the HTML
914 *
915 * @param text the text to be logged
[858]916 */
917function log(text) {
[879]918    if (autoquestDoLog) {
[858]919        var loggingInfo = document.getElementById("loggingInfoParagraph");
920       
921        if (!loggingInfo) {
922            var div = document.createElement("div");
923            div.setAttribute("style", "z-index:1000000; background-color:#afa; " +
[1020]924                             "border:1px black solid; position:absolute; top:10px; right:10px; " +
925                             "width:350px; height:auto; font-size:8pt; font-family:Helvetica");
[858]926           
927            loggingInfo = document.createElement("div");
928            loggingInfo.id = "loggingInfoParagraph";
929            div.appendChild(loggingInfo);
930           
931            var body = document.getElementsByTagName("body")[0];
932            if (!body) {
933                alert("could not enable logging");
934            }
935            else {
936                body.appendChild(div);
937            }
938        }
939       
940        loggingInfo.appendChild(document.createTextNode(text));
941        loggingInfo.appendChild(document.createElement("br"));
942    }
943}
944
[869]945/**
946 * this class represents a single event
947 *
948 * @param type     the type of the event
949 * @param nodePath the path through the HTML DOM to the event target
950 */
[858]951function Event(type, nodePath) {
952    this.type = type;
953    this.nodePath = nodePath;
954    this.time = new Date().getTime();
955   
956    this.setClickCoordinates = function(coordinates) {
957          this.clickCoordinates = coordinates;
958    };
959   
960    this.setKey = function(key) {
961          this.key = key;
962    };
963   
[944]964    this.setSelectedValue = function(value) {
[999]965        this.selectedValue = encodeText(value);
[944]966    };
967 
[858]968    this.setScrollPosition = function(scrollPosition) {
[944]969        this.scrollPosition = scrollPosition;
[858]970    };
971   
972    this.toJSON = function() {
973        var eventInJSON =
974            "{\"path\":\"" + this.nodePath + "\",\"time\":" + this.time + ",\"eventType\":\"" +
975            this.type + "\"";
976
977        if ((this.clickCoordinates) && (!isNaN(this.clickCoordinates[0]))) {
978            eventInJSON += ",\"coordinates\":[" + this.clickCoordinates + "]";
979        }
980
981        if (this.key) {
982            eventInJSON += ",\"key\":" + this.key;
983        }
984       
[944]985        if (this.selectedValue) {
986            eventInJSON += ",\"selectedValue\":\"" + this.selectedValue + "\"";
[858]987        }
[944]988       
989        if ("onscroll" === this.type) {
990            eventInJSON += ",\"scrollPosition\":[" + this.scrollPosition + "]";
991        }
[858]992
993        eventInJSON += "}";
994       
995        return eventInJSON;
996    };
[999]997   
998    function encodeText(text) {
999        return text.replace(/\\/g, "\\\\").replace(/\"/g, "\\\"");
1000    };
[858]1001}
Note: See TracBrowser for help on using the repository browser.