Home | History | Annotate | Download | only in fx
      1 /*
      2  * Content script for Chrome Sounds.
      3  * Tracks in-page events and notifies the background page.
      4  */
      5 
      6 function sendEvent(event, value) {
      7   console.log("sendEvent: " + event + "," + value);
      8   chrome.extension.sendRequest({eventName: event, eventValue: value});
      9 }
     10 
     11 // Timers to trigger "stopEvent" for coalescing events.
     12 var timers = {};
     13 
     14 function stopEvent(type) {
     15   timers[type] = 0;
     16   sendEvent(type, "stopped");
     17 }
     18 
     19 // Automatically coalesces repeating events into a start and a stop event.
     20 // |validator| is a function which should return true if the event is
     21 // considered to be a valid event of this type.
     22 function handleEvent(event, type, validator) {
     23   if (validator) {
     24     if (!validator(event)) {
     25       return;
     26     }
     27   }
     28   var timerId = timers[type];
     29   var eventInProgress = (timerId > 0);
     30   if (eventInProgress) {
     31     clearTimeout(timerId);
     32     timers[type] = 0;
     33   } else {
     34     sendEvent(type, "started");
     35   }
     36   timers[type] = setTimeout(stopEvent, 300, type);
     37 }
     38 
     39 function listenAndCoalesce(target, type, validator) {
     40   target.addEventListener(type, function(event) {
     41     handleEvent(event, type, validator);
     42   }, true);
     43 }
     44 
     45 listenAndCoalesce(document, "scroll");
     46 
     47 // For some reason, "resize" doesn't seem to work with addEventListener.
     48 if ((window == window.top) && document.body && !document.body.onresize) {
     49   document.body.onresize = function(event) {
     50     sendEvent("resize", "");
     51   };
     52 }
     53 
     54 listenAndCoalesce(document, "keypress", function(event) {
     55   if (event.charCode == 13)
     56     return false;
     57 
     58   // TODO(erikkay) This doesn't work in gmail's rich text compose window.
     59   return event.target.tagName == "TEXTAREA" ||
     60          event.target.tagName == "INPUT" ||
     61          event.target.isContentEditable;
     62 });
     63