chrome.events Stay organized with collections Save and categorize content based on your preferences.
Description
Thechrome.events namespace contains common types used by APIs dispatching events to notify you when something interesting happens.
Concepts and usage
AnEvent is an object that lets you be notified when something interesting happens. Here's anexample of using thechrome.alarms.onAlarm event to be notified whenever an alarm has elapsed:
chrome.alarms.onAlarm.addListener((alarm)=>{appendToLog(`alarms.onAlarm -- name:${alarm.name}, scheduledTime:${alarm.scheduledTime}`);});As the example shows, you register for notification usingaddListener(). The argument toaddListener() is always a function that you define to handle the event, but the parameters to thefunction depend on which event you're handling. Checking the documentation foralarms.onAlarm,you can see that the function has a single parameter: analarms.Alarm object that has detailsabout the elapsed alarm.
Example APIs using Events:alarms,i18n,identity,runtime. MostchromeAPIs do.
Declarative Event Handlers
The declarative event handlers provide a means to define rules consisting of declarative conditionsand actions. Conditions are evaluated in the browser rather than the JavaScript engine which reducesroundtrip latencies and allows for very high efficiency.
Declarative event handlers are used for example in theDeclarative Content API. This page describes the underlying concepts of all declarative eventhandlers.
Rules
The simplest possible rule consists of one or more conditions and one or more actions:
construle={conditions:[/* my conditions */],actions:[/* my actions */]};If any of the conditions is fulfilled, all actions are executed.
In addition to conditions and actions you may give each rule an identifier, which simplifiesunregistering previously registered rules, and a priority to define precedences among rules.Priorities are only considered if rules conflict each other or need to be executed in a specificorder. Actions are executed in descending order of the priority of their rules.
construle={id:"my rule",// optional, will be generated if not set.priority:100,// optional, defaults to 100.conditions:[/* my conditions */],actions:[/* my actions */]};Event objects
Event objects may support rules. These event objects don't call a callback function whenevents happen but test whether any registered rule has at least one fulfilled condition and executethe actions associated with this rule. Event objects supporting the declarative API have threerelevant methods:events.Event.addRules(),events.Event.removeRules(), andevents.Event.getRules().
Add rules
To add rules call theaddRules() function of the event object. It takes an array of rule instancesas its first parameter and a callback function that is called on completion.
construle_list=[rule1,rule2,...];addRules(rule_list,(details)=>{...});If the rules were inserted successfully, thedetails parameter contains an array of inserted rulesappearing in the same order as in the passedrule_list where the optional parametersid andpriority were filled with the generated values. If any rule is invalid, for example, because it containedan invalid condition or action, none of the rules are added and theruntime.lastError variableis set when the callback function is called. Each rule inrule_list must contain a uniqueidentifier that is not already used by another rule or an empty identifier.
runtime.onInstalled event. Note that this event isalso triggered when an extension is updated. Therefore, you should first clear previously installedrules and then register new rules.Remove rules
To remove rules call theremoveRules() function. It accepts an optional array of rule identifiersas its first parameter and a callback function as its second parameter.
construle_ids=["id1","id2",...];removeRules(rule_ids,()=>{...});Ifrule_ids is an array of identifiers, all rules having identifiers listed in the array areremoved. Ifrule_ids lists an identifier, that is unknown, this identifier is silently ignored. Ifrule_ids isundefined, all registered rules of this extension are removed. Thecallback()function is called when the rules were removed.
Retrieve rules
To retrieve a list of registered rules, call thegetRules() function. It accepts anoptional array of rule identifiers with the same semantics asremoveRules() and a callback function.
construle_ids=["id1","id2",...];getRules(rule_ids,(details)=>{...});Thedetails parameter passed to thecallback() function refers to an array of rules includingfilled optional parameters.
Performance
To achieve maximum performance, you should keep the following guidelines in mind.
Register and unregister rules in bulk. After each registration or unregistration, Chrome needs toupdate internal data structures. This update is an expensive operation.
construle1={...};construle2={...};chrome.declarativeWebRequest.onRequest.addRules([rule1]);chrome.declarativeWebRequest.onRequest.addRules([rule2]);
construle1={...};construle2={...};chrome.declarativeWebRequest.onRequest.addRules([rule1,rule2]);
Prefer substring matching over regular expressions in anevents.UrlFilter.Substring based matching is extremely fast.
constmatch=newchrome.declarativeWebRequest.RequestMatcher({url:{urlMatches:"example.com/[^?]*foo"}});
constmatch=newchrome.declarativeWebRequest.RequestMatcher({url:{hostSuffix:"example.com",pathContains:"foo"}});
If there are many rules that share the same actions, merge the rules into one.Rules trigger their actions as soon as a single condition is fulfilled. This speeds up thematching and reduces memory consumption for duplicate action sets.
constcondition1=newchrome.declarativeWebRequest.RequestMatcher({url:{hostSuffix:'example.com'}});constcondition2=newchrome.declarativeWebRequest.RequestMatcher({url:{hostSuffix:'foobar.com'}});construle1={conditions:[condition1],actions:[newchrome.declarativeWebRequest.CancelRequest()]};construle2={conditions:[condition2],actions:[newchrome.declarativeWebRequest.CancelRequest()]};chrome.declarativeWebRequest.onRequest.addRules([rule1,rule2]);
constcondition1=newchrome.declarativeWebRequest.RequestMatcher({url:{hostSuffix:'example.com'}});constcondition2=newchrome.declarativeWebRequest.RequestMatcher({url:{hostSuffix:'foobar.com'}});construle={conditions:[condition1,condition2],actions:[newchrome.declarativeWebRequest.CancelRequest()]};chrome.declarativeWebRequest.onRequest.addRules([rule]);
Filtered events
Filtered events are a mechanism that allows listeners to specify a subset of events that they areinterested in. A listener that uses a filter won't be invoked for events that don't pass thefilter, which makes the listening code more declarative and efficient. Aservice worker neednot be woken up to handle events it doesn't care about.
Filtered events are intended to allow a transition from manual filtering code.
chrome.webNavigation.onCommitted.addListener((event)=>{if(hasHostSuffix(event.url,'google.com')||hasHostSuffix(event.url,'google.com.au')){// ...}});
chrome.webNavigation.onCommitted.addListener((event)=>{// ...},{url:[{hostSuffix:'google.com'},{hostSuffix:'google.com.au'}]});
Events support specific filters that are meaningful to that event. The list of filters that an eventsupports will be listed in the documentation for that event in the "filters" section.
When matching URLs (as in the example above), event filters support the same URL matchingcapabilities as expressible with aevents.UrlFilter, except for scheme and port matching.
Types
Event
An object which allows the addition and removal of listeners for a Chrome event.
Properties
- addListener
void
Registers an event listenercallback to an event.
The
addListenerfunction looks like:(callback: H) => {...}
- callback
H
Called when an event occurs. The parameters of this function depend on the type of event.
- addRules
void
Registers rules to handle events.
The
addRulesfunction looks like: [], callback?: function) => {...}(rules: Rule<anyany>
- getRules
void
Returns currently registered rules.
The
getRulesfunction looks like:(ruleIdentifiers?: string[], callback: function) => {...}
- hasListener
void
The
hasListenerfunction looks like:(callback: H) => {...}
- callback
H
Listener whose registration status shall be tested.
- returns
boolean
True ifcallback is registered to the event.
- hasListeners
void
The
hasListenersfunction looks like:() => {...}- returns
boolean
True if any event listeners are registered to the event.
- removeListener
void
Deregisters an event listenercallback from an event.
The
removeListenerfunction looks like:(callback: H) => {...}
- callback
H
Listener that shall be unregistered.
- removeRules
void
Unregisters currently registered rules.
The
removeRulesfunction looks like:(ruleIdentifiers?: string[], callback?: function) => {...}
- ruleIdentifiers
string[] optional
If an array is passed, only rules with identifiers contained in this array are unregistered.
- callback
function optional
The
callbackparameter looks like:() => void
Rule
Description of a declarative rule for handling events.
Properties
- actions
any[]
List of actions that are triggered if one of the conditions is fulfilled.
- conditions
any[]
List of conditions that can trigger the actions.
- id
string optional
Optional identifier that allows referencing this rule.
- priority
number optional
Optional priority of this rule. Defaults to 100.
- tags
string[] optional
Tags can be used to annotate rules and perform operations on sets of rules.
UrlFilter
Filters URLs for various criteria. Seeevent filtering. All criteria are case sensitive.
Properties
- cidrBlocks
string[] optional
Chrome 123+Matches if the host part of the URL is an IP address and is contained in any of the CIDR blocks specified in the array.
- hostContains
string optional
Matches if the host name of the URL contains a specified string. To test whether a host name component has a prefix 'foo', use hostContains: '.foo'. This matches 'www.foobar.com' and 'foo.com', because an implicit dot is added at the beginning of the host name. Similarly, hostContains can be used to match against component suffix ('foo.') and to exactly match against components ('.foo.'). Suffix- and exact-matching for the last components need to be done separately using hostSuffix, because no implicit dot is added at the end of the host name.
- hostEquals
string optional
Matches if the host name of the URL is equal to a specified string.
- hostPrefix
string optional
Matches if the host name of the URL starts with a specified string.
- hostSuffix
string optional
Matches if the host name of the URL ends with a specified string.
- originAndPathMatches
string optional
Matches if the URL without query segment and fragment identifier matches a specified regular expression. Port numbers are stripped from the URL if they match the default port number. The regular expressions use theRE2 syntax.
- pathContains
string optional
Matches if the path segment of the URL contains a specified string.
- pathEquals
string optional
Matches if the path segment of the URL is equal to a specified string.
- pathPrefix
string optional
Matches if the path segment of the URL starts with a specified string.
- pathSuffix
string optional
Matches if the path segment of the URL ends with a specified string.
- ports
(number | number[])[] optional
Matches if the port of the URL is contained in any of the specified port lists. For example
[80, 443, [1000, 1200]]matches all requests on port 80, 443 and in the range 1000-1200. - queryContains
string optional
Matches if the query segment of the URL contains a specified string.
- queryEquals
string optional
Matches if the query segment of the URL is equal to a specified string.
- queryPrefix
string optional
Matches if the query segment of the URL starts with a specified string.
- querySuffix
string optional
Matches if the query segment of the URL ends with a specified string.
- schemes
string[] optional
Matches if the scheme of the URL is equal to any of the schemes specified in the array.
- urlContains
string optional
Matches if the URL (without fragment identifier) contains a specified string. Port numbers are stripped from the URL if they match the default port number.
- urlEquals
string optional
Matches if the URL (without fragment identifier) is equal to a specified string. Port numbers are stripped from the URL if they match the default port number.
- urlMatches
string optional
Matches if the URL (without fragment identifier) matches a specified regular expression. Port numbers are stripped from the URL if they match the default port number. The regular expressions use theRE2 syntax.
- urlPrefix
string optional
Matches if the URL (without fragment identifier) starts with a specified string. Port numbers are stripped from the URL if they match the default port number.
- urlSuffix
string optional
Matches if the URL (without fragment identifier) ends with a specified string. Port numbers are stripped from the URL if they match the default port number.
Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-08-11 UTC.