Skip to content

Proposal: Toggleable event listeners Β #501

@newRoland

Description

@newRoland

There's no good way to make event listeners optional for the background (service worker or event page).

An extension might have an optional feature that requires listening to chatty events. Always having these event listeners active is not ideal, especially when not all users enable that feature. Listening to chatty events impact performance by waking the background frequently or deprive it from rest. Currently, there's no standard method to make event listeners optional. The usual approach of attaching and detaching them is impractical for the background page.

The current workaround is a hacky process that needs to be done every time the background loads.

// on background page start, add the listener. 
browser.webNavigation.onCommitted.addListener(onListener)

// Check if the user has enabled the feature, and if not, remove the listener. 
browser.storage.local.get("someFeature").then(({someFeature}) => {
    update(someFeature) 
})

// Since the feature state can change while the background is on, need to also listen to changes
browser.storage.local.onChanged.addListener(changes => {
    if (changes.someFeature) {
         update(changes.someFeature.newValue) 
    }
})

function update(someFeature) {
     if (someFeature) {
          webNavigation.onCommitted.addListener(onListener)
     } else {
          webNavigation.onCommitted.removeListener(onListener)
     }
}

Proposal

If requiresFlag was specified, the browser will ensure that flag is true before dispatching to the listener.

browser.webNavigation.onCommitted.addListener({
    requiresFlag: "someFlag",
    callback: onListener
})

// In options page, if user enables a feature that needs it. 
browser.runtime.setListenerFlag("someFlag", true) 

// Or to disable 
browser.runtime.setListenerFlag("someFlag", false) 

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions