Jack M
Jack M

Reputation: 5995

Set event handler on arbitrary JS function?

I'd like to write a Chrome extension that works with a particular JS-based chat application. It needs to be made aware every time the chat receives a message.

Now, I can obviously do this easily by setting up a timer and checking to see if $("chat-messages").childElements().length has increased, but I'd rather go with the more elegant method of setting up an event handler of some sort to fire every time appendChatMessage() is invoked. Is there a way to do this?

var oldfunc = appendChatMessage;
appendChatMessage = function() { eval(oldfunc); myChatMessageReceivedHandler(); }

Doesn't seem to be working.

Upvotes: 0

Views: 243

Answers (4)

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18344

You have to do oldfunc(). Besides that I'd create an event to to that

var oldfunc = appendChatMessage;
appendChatMessage = function() { oldfunc(); $(document).trigger("msg_received"); }

$(document).bind("msg_received", function(params){
   //do your logic when message arrives
});

You should decide which element to attach the event into and its params.

Hope this helps. Cheers

Upvotes: 3

pomeh
pomeh

Reputation: 4912

If there is a method appendChatMessage that is called every time a new message arrives, you could do like this

var old = appendChatMessage;
appendChatMessage = function() {
    // call the initial method and store the result
    var result = old.apply( this, arguments );

    // do your stuff here

    // return the initial result
    return result;
};

Upvotes: 3

Pablo Fernandez
Pablo Fernandez

Reputation: 105220

var f = function () { console.log('foo'); }

var f2 = f;

f = function () { f2(); console.log('bar'); }

This should print:

foo

bar

Upvotes: 0

Ry-
Ry-

Reputation: 224904

var oldfunc = appendChatMessage;
appendChatMessage = function() { eval(oldfunc(); myChatMessageReceivedHandler(); }

Should work, depending on the context.

Upvotes: 1

Related Questions