Search code examples
javascriptgoogle-chrome-extension

How can I make the popup code wait for the background code to finish before moving to the next line?


popup.js:

chrome.runtime.getBackgroundPage((bg) => {    
     bg.createTabObj();                 
     Volume.init();                                             
     });

background.js:

createTabObj() {
    chrome.tabCapture.capture({
            audio: true,
            video: false
        },
        (stream) => {                                                     
            //do something                                         
        })

As it is, the popup continues to the next second line before the background method finished its process. What's the simplest way to make sure that the background finishes processing the createTabObj methods before the popup continues to Volume.init()? I prefer doing all the calls from the popup instead of a background callback, if possible.


Solution

  • The second part of the chrome.tabCapture.capture is a callback function. Just call the Volume.init() inside that callback function.

    chrome.runtime.getBackgroundPage((bg) => {    
       bg.createTabObj(Volume.init);                                             
    });
    
    createTabObj(id, yourcallback) {
        chrome.tabCapture.capture({
                audio: true,
                video: false
            },
            (stream) => {      
                yourcallback();                                               
                //do something                                         
            })
    
    

    I'm not sure where your id for createTabObj is being passed in though, but I hope I got the general idea across.