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.
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;
};
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
var oldfunc = appendChatMessage; appendChatMessage = function() {eval(oldfunc(); myChatMessageReceivedHandler(); }
Should work, depending on the context.
var f = function () { console.log('foo'); }
var f2 = f;
f = function () { f2(); console.log('bar'); }
This should print:
foo
bar
精彩评论