'Re-execute React Effect on URL change for Chrome Extension
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?
Solution 1:[1]
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:
- onActivated
- onActiveChanged
- onAttached
- onCreated
- onDetached
- onHighlightChanged
- onHighlighted
- onMoved
- onRemoved
- onReplaced
- onSelectionChanged
- onUpdated
- onZoomChange
you might want to find what suits your case better by checking chrome DOCS.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Cesare Polonara |
