Kuldeep Daftary
Kuldeep Daftary

Reputation: 621

How to check if the function is called from foreign js file

There's a foreign JS file which is not loaded from our server on my page. In short I dont have any control on that file and I can't edit the file. I have created 1 function which I wish to call after the function which is in that foreign file is called.

I know the name of function of foreign file. I wish to call my function once the function from foreign file is executed. How can I do it?

Let me know if you dont understand my problem here. I'll try and explain it again.

Thanks in advance

Upvotes: 1

Views: 299

Answers (2)

Alnitak
Alnitak

Reputation: 339917

If the foreign function is in the global scope you can replace it with your own wrapper:

var _old = foreignFunction;
foreignFunction = function() {

    // put pre-call stuff here
    ...

    // call with the original context and args
    _old.apply(this, arguments);  

    // and post-call stuff here
    ...
}

Note the use of .apply to ensure that whatever context and arguments were supplied to the original function are still supplied to it. Without that, the this variable inside that function may not be what it's supposed to be.

Upvotes: 5

scaryman
scaryman

Reputation: 1900

You have to replace the foreign function with your own. This may or may not be possible, depending on the order in which things are executed.

After the function (ForeignFunc()) is loaded onto the page

var _originalForeignFunc = ForeignFunc;
ForeignFunc = function() {
    _originalForeignFunc();
    //now do whatever you want to do here
    alert("After Foreign Func Execution");
}

Just remember, this will only work if you can replace ForeignFunc() with your own definition before it's actually called.

Upvotes: 2

Related Questions