javascriptgoogle-chromegoogle-chrome-extensionchrome-extension-manifest-v3

(Chrome Extension) Playing music in the background


I'm creating a music player extension in Chrome, and I'm using Manifest V3 since V2 is being phased out. However with the restrictions that manifest V3 and service workers presents such as not being able to access the DOM, I've been wondering for a while if and how I can play music in the background (with the extension not being shown). Does anybody know how to do it with MV3?


Solution

  • In the background (aka service worker) you can't.
    Nowadays, there are 2-3 options. You can:

    1. open an extension page in a new tab\window which plays the sound.
    2. inject a content script into an already existing tab which does the same thing as step #1.
    3. wait to "offScreenDocument" be add in stable channell of Chrome (if you choose this last option then treat yourself a new comfortable armchair)

    EDIT

    In response to your righteous considerations...
    Personally I would suggest the 1st option. I tested the third option in Chrome Canary but I never test the second one.
    Fears about restarting music (following option #2) can potentially be allayed injecting programmatically and checking (via message exchange) whether there is an injected script which it is already playing.
    However, if the tab where the cs was injected is closed then it'd be necessary to inject on another tab or create a new one in fact by actually "jumping" (as you wrote), the reproduction.
    Another sore point is that, following method #2 you will have to define your c.s. with the "match" clause set to "<all_urls>" which could greatly lengthen the waiting time for a possible publication on the CWS and "scared" your user.
    Another less important aspect is that if there were no more tabs elegible for "injection" the music would stop.
    Finnally, I'm wondering whether the little audio icon on tab label appers in injected tab (it'd not so good to see)