How can I refresh a content-script view that's located on an inactive tab?

228 views
Skip to first unread message

Richard Pölderl

unread,
Sep 22, 2022, 9:08:27 AM9/22/22
to Chromium Extensions
Is it possible to update a tab that's not active from the background script?

Use Case
Please see this walkthrough for an easier visualisation. Here are the steps:
  • a user opens my extension on a page, e.g. "example.com"
  • the extension shows a "Sign in with Google" page (user isn't authenticated yet)
  • onClick of that button, a new tab opens the google oauth flow
  • after the oauth flow, the user is sent to my own domain "my-domain.com/login/success"
  • on that page, I send a message via chrome.runtime.sendMessage(EXTENSION_ID, {message: "refreshInitiationTab"})
  • my background.ts file has the chrome.runtime.onMessageExternal.addListener() that logs the incoming message correctly
  • -> what I want to do know is to refresh my extension view on the tab but I'm unable to communicate to it.
The APIs I've tried
  • chrome.tabs.sendMessage(tab.id), where I get the tabId from the chrome.tabs.update() which correctly focuses the previous tab | Problem: Could not establish connection. Receiving end does not exist.
  • chrome.tabs.connect(tab.id, {name: "foo"}), where my content-script has a listener for that port | Problem: I can see that my content-script's console shows that my connection is disconnected after navigating to the new tab (verifying by using the port.onDisconnect.addListener in the content-script). I'm unable to re-establish the connection to that content-script from the background even though I have the tabId. 🤔

How a simplified implementation looks from my side:
```
// in my content-script (via react)
const init = async () => {
  chrome.runtime.onConnect.addListener((port) => {
    console.log("hi") // ❌ doesn't log if I navigate to the tab
    if (port.name == "refreshTabAfterAuthentication") {
      port.onMessage.addListener(() => forceUpdate())
    }
  })
}

useEffect(() => init(), []) 

// in my background.ts (MV3)
// ...in some onMessage handler:
const port = chrome.tabs.connect(toRefresh.signInInitiatedBy.tabId, { name: "refreshTabAfterAuthentication" })
port.postMessage({ toRefresh.signInInitiatedBy.url })

 

wOxxOm

unread,
Sep 22, 2022, 11:20:30 AM9/22/22
to Chromium Extensions, richard....@gmail.com
There's no such limit in chrome extensions API. It's probable that React uses requestAnimationFrame, which doesn't fire in inactive tabs. They can also check document.hasFocus() and listen to `blur` event.
Reply all
Reply to author
Forward
0 new messages