Search code examples
javascriptfirefoxbackgroundfirefox-addon

How to change the active a tab on another window in a browser extension?


I am trying to develop a Firefox Extension. I want to go to a browser tab on a different window. As I can understand from the Firefox Browser Extensions API I can change the focused window and I can change the active tab on the focused window separately. Thus, I wrote the code below to my background script to achieve this. However, when I use this code the browser first changes the focus to the window with the previously active tab of that window and then activates the tab that I want on that window. This behavior causes a glitchy feel.

browser.windows.update(windowId, {focused:true})
browser.tabs.update(tabId,{active:true})

Can you suggest me a way to go to a specific tab on another window at one operation?

Thank you in advance!


Solution

  • As Piro inspired me to first activate the tab and the change the focus of the window I tried the two code pieces below. However, in both of them tab activation could not keep up with the windows focus change and resulted the same glitchy feel.

    browser.tabs.update(tabId,{active:true})
    browser.windows.update(windowId, {focused:true})
    
    
    browser.tabs.update(tabId,{active:true}).then(() =>
     browser.windows.update(windowId, {focused:true})
    )
    

    Finally I just implemented the following which sleeps a while before changing the window focus. With optimizing the sleep duration to 50 ms I got a smooth experience.

    browser.tabs.update(audibleTabs[0].id,{active:true})
    setTimeout(() => 
        browser.windows.update(window.id, {focused:true})
    , 50);
    

    Chrome Edit: I tried to run my extension on Chrome and experienced that 50ms sleep was not enogh for Chrome. Thus, I optimized the sleep time to 150ms for Chrome.