Reputation: 1866
I have a document I'm working on as part of a much larger site. A lot of scripts are loaded in automatically, but one is breaking things and I don't know how it's included. I can't remove it because it's needed elsewhere (it does event listeners), but it serves no purpose for the part of code I'm running other to cause a pointless page refresh which ruins the users' work (and then, only in chrome).
To that end, is there a way in javascript to turn off another source script, and then turn it back on later?
I don't have the option of modifying the target script itself or keep it from being initially included in the document.
Upvotes: 0
Views: 85
Reputation: 20899
Sort of...
you can always store any JavaScript method inside a variable, replace it's implementation, do your own stuff and finally restore it.
From your question it is unclear if this might be a solution for your Problem, I just mention this because of all the "Not possible" comments.
https://jsfiddle.net/3grfL30s/
function alertSomething(cp){
alert("TEST: " + cp);
}
alertSomething(1);
// from here i dont want alerts, no matter what code is calling the method
// backup method to "x" to restore it later.
var x = alertSomething;
alertSomething = function(){} //overwrite alertSomething to do nothing
//do my work, verify alertSomething is doing nothing
alertSomething(2);
//restore alert method
alertSomething = x;
//verify its working agian
alertSomething(3);
This would produce the alerts 1
and 3
, even if 2
would have been called while your code is beeing executed.
For more complex methods or non-boolean execution conditions, the Proxy Pattern with additional "flags" can be useful (Example still boolean, but there could be multiple conditions):
https://jsfiddle.net/3grfL30s/1/
function alertSomething(cp){
alert("TEST: " + cp);
}
var doIt = 1;
var originalAlert = alertSomething;
alertSomething = function(cp){
if (doIt){
return originalAlert.apply(this, arguments);
}
}
alertSomething(1);
// in here i dont want alerts
doIt = 0;
//do my work, verify alertSomething is doing nothing
alertSomething(2);
//restore alert method
doIt = 1;
//verify its working agian
alertSomething(3);
Upvotes: 2