views:

611

answers:

2

I'm trying to write a Greasemonkey script that works with Gmail. I know how to create javascript that reacts to the user clicking on the Inbox link or the the Refresh link. My problem is that Gmail periodically refreshes the inbox with new conversations and I have no way of capturing this event. Is there any way to capture periodical Ajax events in javascript?

+1  A: 

You could try replacing the window.setTimeout function (and possibly window.setInterval) with your own functions:

window._setTimeout = window.setTimeout;
window.setTimeout = function(func, delay) {
    return window._setTimeout(function() {
        // Your code goes here, before the client function is called
        alert('A timeout event just fired!');

        if (typeof func == 'string') {
            eval(func);
        } else {
            func();
        }
    }, delay);
}
Miles
This is a great idea. Unfortunately, it's not working for me so far. I've tried replacing both the window.setTimeout and the window.setInterval and I'm not getting any alerts. I wonder if Gmail has already called these functions before I replace them in the Greasemonkey script.
Ben Mills
I even tested that replacing the setTimeout and setInterval functions works by calling them in the Greasmonkey script. As expected, I see alerts. My problem seems to be that Gmail has already called setTimeout or setInterval before the Greasemonkey script runs.
Ben Mills
A: 

I tried Miles' excellent suggestion above, but unfortunately it doesn't work because Gmail has already called the original setTimeout function before I have a chance to change it in my Greasemonkey script.

The only thing I can do is somehow react to the changes that Gmail makes when it periodically refreshes the inbox. I found that there are several DOM related events that fire when a node is added or removed:

http://www.w3.org/TR/DOM-Level-3-Events/events.html#event-DOMNodeInserted

Since Gmail is updating the DOM with my latest emails, I can listen for these DOM events (I'm using DOMNodeInserted) and react to the changes.

It isn't elegant, but it works.

Ben Mills