Search code examples
javascripttabsfirefox-addonuserscripts

How to mute active browser tab programatically with JS tabs API?


I'm trying to build a simple userscript to automatically mute tabs matching a certain URL. I'm trying to start simple, just muting the active tab if it matches the URL. Here's the code I would expect to perform the mute action:

browser.tabs.update({muted: true});

But when I try to run it, nothing happens. From the tabs.update documentation I know I don't have to specify a tab ID if I'm working with the active tab, but it also says that this function returns a Promise, and I'm not familiar with how that affects things. (Every example I can find of a Promise uses the .then method to call specific actions after the Promise is completed, e.g. writing console output. But I don't need anything to happen afterwards, I just want it to happen.)

Can anyone help figure out why this code isn't working?

(Note: I'm running userscripts on Firefox using the Firemonkey extension.)


Solution

  • browser.tabs.update({muted: true});

    Above API is in browser scope (for browser & extensions) and is not available in userScript or content scope where user-scripts run.

    In user-scripts, you need to use Web API.

    Here is an idea that you can work on .... not tested

    document.querySelectorAll('audio, video').forEach(item => {
      item.muted = true;
      item.pause();
    });