-
-
Notifications
You must be signed in to change notification settings - Fork 92
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Best effort to run webRequest.onHeaderReceived listener last (issue #6)
- Loading branch information
1 parent
2250d51
commit 8caa253
Showing
3 changed files
with
75 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
/** | ||
* Wrapper around listeners on various WebExtensions | ||
* APIs (e.g. webRequest.on*), as a best effort to | ||
* let them run last by removing and re-adding them | ||
* on each call (swapping 2 copies because | ||
* addListener() calls are asynchronous). | ||
* Note: we rely on implementation details Like | ||
* listeners being called in addition order; also, | ||
* clients should ensure they're not called twice for | ||
* the same event, if that's important. | ||
} | ||
*/ | ||
|
||
class LastListener { | ||
constructor(observed, listener, ...extras) { | ||
this.observed = observed; | ||
this.listener = listener; | ||
this.extras = extras; | ||
let ww = this._wrapped = [listener, listener].map(l => { | ||
let w = (...args) => { | ||
if (this.observed.hasListener(w._other)) { | ||
this.observed.removeListener(w._other); | ||
if (this.last === w) return this.defaultResult; | ||
} else if (this.installed) { | ||
this.observed.addListener(w._other, ...this.extras); | ||
this.last = w._other; | ||
} | ||
return this.installed ? this.listener(...args) | ||
: this.defaultResult; | ||
} | ||
return w; | ||
}); | ||
|
||
ww[0]._other = ww[1]; | ||
ww[1]._other = ww[0]; | ||
this.installed = false; | ||
this.defaultResult = null; | ||
} | ||
|
||
install() { | ||
if (this.installed) return; | ||
this.observed.addListener(this._wrapped[0], ...this.extras); | ||
this.installed = true; | ||
} | ||
|
||
uninstall() { | ||
this.installed = false; | ||
for (let l of this._wrapped) this.observed.removeListener(l); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters