Open bershanskiy opened 1 year ago
It must be optional to avoid subtle changes in behavior for extensions that want to listen at the end of the dispatch chain. For example Tampermonkey/Violentmonkey listens to DOMContentLoaded to wait for the page to finish its DOMContentLoaded listeners and change DOM so that the userscripts will run afterwards and see a more finalized version of DOM.
It can be a parameter in addEventListener (Chrome team dislikes this usually) or a dedicated chrome.dom.setListenerPriority calling which would synchronously change the mode for all subsequent addEventListener calls.
Background
When JS registers a listener for a particular event on a particular object, that event listener is appended to the end of target's event listener list.[1] When event is being dispatched, the browser iterates over the list in order and fires events in order. In practice, this gives a rise to a race condition between page's own event listener registrations and extension's own.
Problem
Some pages intentionally cancel some events. Extensions which want to observe a particular event on the page despite that event being cancelled have to set
run_at
value todocument_start
and immediately register an event listener ondocument
withcapture
set totrue
. Running a large script atdocument_start
is typically bad for performance while registering a multiple content scripts (a dedicated script only to intercept event, and then also the regular script) increases complexity.Proposal
Event handlers registered by extension on a particular target run before all other event handlers registered by the page.
[1] https://dom.spec.whatwg.org/#ref-for-dom-eventtarget-addeventlistener%E2%91%A2