I’m working on a userscript for Gmail and running into an issue. I can easily detect when users manually click the inbox or refresh buttons, but Gmail also automatically updates the inbox in the background to show new emails. These automatic updates happen through AJAX requests that I can’t seem to catch. Is there a method in JavaScript to monitor these background AJAX calls that occur without any user clicks? I need to run some code whenever the inbox gets updated, whether it’s manual or automatic.
Try using MutationObserver instead - it watches for DOM changes in Gmail’s inbox container. Gmail updates the inbox by changing the DOM structure when new emails come in, so you can catch these changes without messing with network requests. Just set up an observer on the email list container and watch for childList changes and subtree modifications. This works way better than network interception because it catches the actual inbox updates no matter how Gmail handles the backend stuff. I’ve used this in several Gmail userscripts and it works great. The observer fires consistently whether updates come from user clicks or automatic refreshes. Just remember to debounce the callback since Gmail can trigger multiple DOM changes for one inbox update.
u could also hook into Gmail’s internal events if u can access them. Gmail fires custom events when the inbox changes, but they’re buried in their JS framework. Another option - monitor the browser’s performance API since it tracks all network requests, incl. background ones. just use performance.getEntriesByType(‘resource’) and filter for Gmail’s API calls. it’s hacky but works pretty well.
You need to intercept both XMLHttpRequest and fetch calls globally - Gmail uses both for AJAX stuff. I’ve run into this building browser extensions for webmail before. The key is overriding the native XMLHttpRequest prototype and fetch function before Gmail’s scripts load. Wrap the original XMLHttpRequest send method and watch responses through onreadystatechange. For fetch, override the global function and return a promise that resolves after you process the response. Gmail’s internal API endpoints change all the time, so filter requests by URL patterns that show inbox updates. I’ve found monitoring responses works better than requests - you can actually check if the response has new email data before your code runs.
This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.