简体   繁体   中英

Chrome-Extension eventHandler in React

I'm currently trying to build a Chrome extension. To do this I'm using a react app. All the rendering and stuff is working. The problems are the chrome event handlers.

In my react app I have a context.

Inside this context is a useEffect hook where I register the events:

useEffect(() => {
  chrome.tabs.onUpdated.addListener(myListener)
}, []);

The listener function uses variables from useState within the context so I have to update the listener every time these variables change.

Of course there is the removeEventListener function, but when I call it, it does nothing because the function has already changed, and because of this Chrome thinks there is no such listener registered.

Does anyone know how to remove the old listeners or just clear all listeners?

Solution code snippet:

const handlerRef = useRef();
useEffect(() => {
    if(handlerRef.current){
        chrome.yourField.yourUpdate.removeListener(handlerRef.current);
    }
    chrome.yourField.yourUpdate.addListener(handler);
}, [yourDependencies]);
useEffect(() => {
     handlerRef.current = handler;
});

Thanks to @wOxxOm!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM