3

There are several elements on HTML page which triggers a js function HardCoded(). I cannot modify HardCoded() function.

I want to run some custom js code after the HardCoded() function is getting called. How can I do that? Is there any handlers for js functions?

I'm building a chrome extension that's why I cannot modify page source code.
I have access to JQuery.

One way is to find all elements who are calling HardCoded() and attach events to those elements but I would like to avoid this method.

11
  • Is there a good reason you can't modify HardCoded? Commented Feb 9, 2018 at 21:43
  • 1
    Have a look: stackoverflow.com/questions/3406467/…
    – PM 77-1
    Commented Feb 9, 2018 at 21:44
  • If you really cannot, just chain the handler and wrap the hardcoded call in a promise Commented Feb 9, 2018 at 21:44
  • what does HardCoded do? Is it making a DOM change that you can watch for? If you cant edit the function to add a callback, then you will need to determine what changes you can watch for when the function fires.
    – Korgrue
    Commented Feb 9, 2018 at 21:44
  • @SterlingArcher this is for building chrome extension so cant modify
    – GorvGoyl
    Commented Feb 9, 2018 at 21:45

1 Answer 1

5

You could do something like this:

var oldFn = HardCoded;
window.HardCoded = function(){
   var res = oldFn.apply(this, arguments);
   // New Code ....
   return res;
}

What this does is to create a reference to the HardCoded function, redefine this function and then call the old implementation using the previously created reference.

6
  • StackOverflow (too many recursions) detected! Try to execute HardCode()
    – Ele
    Commented Feb 9, 2018 at 21:47
  • 1
    Make sure you pass the arguments along Commented Feb 9, 2018 at 21:49
  • 1
    Still going to say: Uncaught RangeError: Maximum call stack size exceeded Commented Feb 9, 2018 at 21:51
  • 3
    hoisting is why this fails.
    – Kevin B
    Commented Feb 9, 2018 at 21:52
  • It needs to be declared as var oldFn = HardCoded; HardCoded = function (){ Commented Feb 9, 2018 at 21:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.