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