I am using React in a Chrome Extension where the extension's content.js loads the index.html of the compiled React app.
In the React app, an effect prints out the current tab's domain in the JS console when the app first loads, due to having a dependency of [].
function App() {
useEffect(() => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const url = new URL(tabs[0].url);
const domain = url.hostname;
console.log("Domain:", domain);
});
}, []);
...
}
Is it possible to modify this such that the effect is executed again everytime the tab is navigated to another URL?
You should subscribe to chrome.tabs changes:
function App() {
useEffect(() => {
chrome.tabs.onUpdated.addListener(queryTabs)
}, []);
const queryTabs = (id, info, tab) => {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
// Do something with tabs
const url = new URL(tabs[0].url);
const domain = url.hostname;
console.log("Domain:", domain);
});
}
...
}
You have a lot of tab events that you can subscribe to, I chose update for sake of simplicity:
you might want to find what suits your case better by checking chrome DOCS.