Home | History | Annotate | Download | only in intros
      1 <p>
      2 An <code>Event</code> is an object
      3 that allows you to be notified
      4 when something interesting happens.
      5 Here's an example of using the
      6 <code>chrome.alarms.onAlarm</code> event
      7 to be notified whenever an alarm has elapsed:
      8 </p>
      9 
     10 <pre>
     11 chrome.alarms.onAlarm.<b>addListener(function(</b>alarm<b>) {</b>
     12   appendToLog('alarms.onAlarm --'
     13               + ' name: '          + alarm.name
     14               + ' scheduledTime: ' + alarm.scheduledTime);
     15 <b>});</b>
     16 </pre>
     17 
     18 <p>
     19 As the example shows,
     20 you register for notification using <code>addListener()</code>.
     21 The argument to <code>addListener()</code>
     22 is always a function that you define to handle the event,
     23 but the parameters to the function depend on
     24 which event you're handling.
     25 Checking the documentation for
     26 $ref:alarms.onAlarm,
     27 you can see that the function has a single parameter:
     28 an $ref:alarms.Alarm object
     29 that has details about the elapsed alarm.
     30 </p>
     31 
     32 
     33 {{^is_apps}}
     34 <div class="doc-family extensions">
     35 <h2 id="declarative">Declarative Event Handlers</h2>
     36 
     37 <p>
     38 The declarative event handlers provide a means to define rules consisting of
     39 declarative conditions and actions. Conditions are evaluated in the browser
     40 rather than the JavaScript engine which reduces roundtrip latencies and allows
     41 for very high efficiency.
     42 </p>
     43 
     44 <p>Declarative event handlers are used for example in the <a
     45 href="declarativeWebRequest.html">Declarative Web Request API</a> and <a
     46 href="declarativeContent.html">Declarative Content API</a>. This page describes
     47 the underlying concepts of all declarative event handlers.
     48 </p>
     49 
     50 <h3 id="rules">Rules</h3>
     51 
     52 <p>The simplest possible rule consists of one or more conditions and one or more
     53 actions:</p>
     54 <pre>
     55 var rule = {
     56   conditions: [ /* my conditions */ ],
     57   actions: [ /* my actions */ ]
     58 };
     59 </pre>
     60 
     61 <p>If any of the conditions is fulfilled, all actions are executed.</p>
     62 
     63 <p>In addition to conditions and actions you may give each rule an identifier,
     64 which simplifies unregistering previously registered rules, and a priority to
     65 define precedences among rules. Priorities are only considered if rules conflict
     66 each other or need to be executed in a specific order. Actions are executed in
     67 descending order of the priority of their rules.</p>
     68 
     69 <pre>
     70 var rule = {
     71   id: "my rule",  // optional, will be generated if not set.
     72   priority: 100,  // optional, defaults to 100.
     73   conditions: [ /* my conditions */ ],
     74   actions: [ /* my actions */ ]
     75 };
     76 </pre>
     77 
     78 <h3 id="eventobjects">Event objects</h3>
     79 
     80 <p>
     81 <a href="events.html">Event objects</a> may support rules. These event objects
     82 don't call a callback function when events happen but test whether any
     83 registered rule has at least one fulfilled condition and execute the actions
     84 associated with this rule. Event objects supporting the declarative API have
     85 three relevant methods: $ref:events.Event.addRules,
     86 $ref:events.Event.removeRules, and
     87 $ref:events.Event.getRules.
     88 </p>
     89 
     90 <h3 id="addingrules">Adding rules</h3>
     91 
     92 <p>
     93 To add rules call the <code>addRules()</code> function of the event object. It
     94 takes an array of rule instances as its first parameter and a callback function
     95 that is called on completion.
     96 </p>
     97 
     98 <pre>
     99 var rule_list = [rule1, rule2, ...];
    100 function addRules(rule_list, function callback(details) {...});
    101 </pre>
    102 
    103 <p>
    104 If the rules were inserted successfully, the <code>details</code> parameter
    105 contains an array of inserted rules appearing in the same order as in the passed
    106 <code>rule_list</code> where the optional parameters <code>id</code> and
    107 <code>priority</code> were filled with the generated values. If any rule is
    108 invalid, e.g., because it contained an invalid condition or action, none of the
    109 rules are added and the 
    110   $ref:runtime.lastError variable is set when
    111 the callback function is called. Each rule in <code>rule_list</code> must
    112 contain a unique identifier that is not currently used by another rule or an
    113 empty identifier.
    114 </p>
    115 
    116 <p class="note">
    117 <strong>Note:</strong> Rules are persistent across browsing sessions. Therefore,
    118 you should install rules during extension installation time using the
    119 <code>$ref:runtime.onInstalled</code>
    120 event. Note that this event is also triggered when an extension is updated.
    121 Therefore, you should first clear previously installed rules and then register
    122 new rules.
    123 </p>
    124 
    125 <h3 id="removingrules">Removing rules</h3>
    126 
    127 <p>
    128 To remove rules call the <code>removeRules()</code> function. It accepts an
    129 optional array of rule identifiers as its first parameter and a callback
    130 function as its second parameter.
    131 </p>
    132 
    133 <pre>
    134 var rule_ids = ["id1", "id2", ...];
    135 function removeRules(rule_ids, function callback() {...});
    136 </pre>
    137 
    138 <p>
    139 If <code>rule_ids</code> is an array of identifiers, all rules having
    140 identifiers listed in the array are removed. If <code>rule_ids</code> lists an
    141 identifier, that is unknown, this identifier is silently ignored. If
    142 <code>rule_ids</code> is <code>undefined</code>, all registered rules of this
    143 extension are removed. The <code>callback()</code> function is called when the
    144 rules were removed.
    145 </p>
    146 
    147 <h3 id="retrievingrules">Retrieving rules</h3>
    148 
    149 <p>
    150 To retrieve a list of currently registered rules, call the
    151 <code>getRules()</code> function. It accepts an optional array of rule
    152 identifiers with the same semantics as <code>removeRules</code> and a callback
    153 function.
    154 </p>
    155 
    156 <pre>
    157 var rule_ids = ["id1", "id2", ...];
    158 function getRules(rule_ids, function callback(details) {...});
    159 </pre>
    160 
    161 <p>
    162 The <code>details</code> parameter passed to the <code>callback()</code> function
    163 refers to an array of rules including filled optional parameters.
    164 </p>
    165 
    166 <h3 id="performance">Performance</h3>
    167 
    168 <p>
    169 To achieve maximum performance, you should keep the following guidelines in
    170 mind:
    171 <ul>
    172   <li><p>Register and unregister rules in bulk. After each
    173   registration or unregistration, Chrome needs to update internal data
    174   structures. This update is an expensive operation.</p>
    175   <p>Instead of</p>
    176   <pre>
    177 var rule1 = {...};
    178 var rule2 = {...};
    179 chrome.declarativeWebRequest.onRequest.addRules([rule1]);
    180 chrome.declarativeWebRequest.onRequest.addRules([rule2]);</pre>
    181   <p>prefer to write</p>
    182   <pre>
    183 var rule1 = {...};
    184 var rule2 = {...};
    185 chrome.declarativeWebRequest.onRequest.addRules([rule1, rule2]);</pre>
    186   <li>Prefer substring matching over matching using regular expressions in a
    187   $ref:events.UrlFilter.  Substring based matching is extremely fast.
    188   <p>Instead of</p>
    189   <pre>
    190 var match = new chrome.declarativeWebRequest.RequestMatcher({
    191     url: {urlMatches: "example.com/[^?]*foo" } });</pre>
    192   <p>prefer to write</p>
    193   <pre>
    194 var match = new chrome.declarativeWebRequest.RequestMatcher({
    195     url: {hostSuffix: "example.com", pathContains: "foo"} });</pre>
    196   <li>If you have many rules that all share the same actions, you may merge
    197   the rules into one because rules trigger their actions as soon as a single
    198   condition is fulfilled. This speeds up the matching and reduces memory
    199   consumption for duplicate action sets.
    200   <p>Instead of</p>
    201   <pre>
    202 var condition1 = new chrome.declarativeWebRequest.RequestMatcher({
    203     url: { hostSuffix: 'example.com' } });
    204 var condition2 = new chrome.declarativeWebRequest.RequestMatcher({
    205     url: { hostSuffix: 'foobar.com' } });
    206 var rule1 = { conditions: [condition1],
    207               actions: [new chrome.declarativeWebRequest.CancelRequest()]};
    208 var rule2 = { conditions: [condition2],
    209               actions: [new chrome.declarativeWebRequest.CancelRequest()]};
    210 chrome.declarativeWebRequest.onRequest.addRules([rule1, rule2]);</pre>
    211   <p>prefer to write</p>
    212   <pre>
    213 var rule = { conditions: [condition1, condition2],
    214              actions: [new chrome.declarativeWebRequest.CancelRequest()]};
    215 chrome.declarativeWebRequest.onRequest.addRules([rule]);</pre>
    216 </ul>
    217 </p>
    218 </div>
    219 {{/is_apps}}
    220 
    221 {{^is_apps}}
    222 <div class="doc-family extensions">
    223 <h2 id="filtered">Filtered events</h2>
    224 
    225 <p>Filtered events are a mechanism that allows listeners to specify a subset of
    226 events that they are interested in. A listener that makes use of a filter won't
    227 be invoked for events that don't pass the filter, which makes the listening
    228 code more declarative and efficient - an <a href="event_pages.html">event
    229   page</a> page need not be woken up to handle events it doesn't care
    230 about.</p>
    231 
    232 <p>Filtered events are intended to allow a transition from manual filtering
    233 code like this:</p>
    234 
    235 <pre>
    236 chrome.webNavigation.onCommitted.addListener(function(e) {
    237   if (hasHostSuffix(e.url, 'google.com') ||
    238       hasHostSuffix(e.url, 'google.com.au')) {
    239     // ...
    240   }
    241 });
    242 </pre>
    243 
    244 <p>into this:</p>
    245 
    246 <pre>
    247 chrome.webNavigation.onCommitted.addListener(function(e) {
    248   // ...
    249 }, {url: [{hostSuffix: 'google.com'},
    250           {hostSuffix: 'google.com.au'}]});
    251 </pre>
    252 
    253 <p>Events support specific filters that are meaningful to that event. The list
    254 of filters that an event supports will be listed in the documentation for that
    255 event in the "filters" section.</p>
    256 
    257 <p>When matching URLs (as in the example above), event filters support the same
    258 URL matching capabilities as expressible with a
    259   $ref:events.UrlFilter, except for scheme and port
    260 matching.</p>
    261 
    262 </div>
    263 {{/is_apps}}
    264