How to remove all scripts in page, even those attached to events and timers?
I am experimenting with JavaScript & I can't seem to understand simple behavior. What I want to do, is to disable absolutely any JS that was before the following code snippet:
void (function(){
(function prepare(name){
var elements = document.getElementsByTagName(name);
for(var i = elements.length; i--;)
elements[i].parentNode.removeChild(elements[i]);
return prepare;
}('script'));
}());
NOTE Marcel Korpel: indenting inserted for readability, but yo开发者_开发百科u should paste this as one line-of-code in the address bar.
The following code theoretically should disabled all the JS on the page, right? To test it, you can execute it via javascript: [..]
when the page is fully loaded. FireBug HTML will show that all scripts are removed. However, there were things in code like setTimeout
, setInterval
, binding specific actions, on click events, etc. and they still work even after the code is executed.
Is there a way to completely remove all of this after the script is executed?
Unfortunately, timeouts (as in setTimeout
) and intervals (setInterval
) are opaque. This means there is no way to cancel running timeout/interval w/o knowing its handle. Same is for event listeners, DOM object's event sink is not available, so no way to removeEventListener
without knowledge how addEventListener
was called.
The only way i can figure out is user javascript in Opera, where you can hook functions listed above and keep track of timeouts/intervals/listeners.
After the script evaluation, you can't remove JavaScript that way. If you know the object needed to delete, you can use the brute-force way:
for (var key in window) {
window[key] = undefined;
}
but it doesn't remove events.
Events are complicated, depends on what kind of event system used... The old DOM events can be removed with recursive iteration on DOM and removing any kind of event attribute on the DOM elements.
Modern event system can be disabled a bit tricky:
document.body.innerHTML = document.body.innerHTML +'';
But this solution have some possible memory leaks.
精彩评论