Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a way to restore the native escape function after it has been overwritten?

Tags:

javascript

I didn't know you could do this until I had banged my head against the wall on a troublesome bug and finally figured out we were failing because some jquery plugin had overwritten the escape function. So this will put up an alert and docwrite null:

escape = function(a){alert(a)}
document.write(escape("Need tips? Visit W3Schools!"));

Cool! (not).

Is there a way to restore the native escape function?

like image 644
dfinnecy Avatar asked Jun 24 '10 06:06

dfinnecy


2 Answers

Create an iframe and get the function from it:

function retrieveNative(native) {
  var iframe = document.createElement('iframe');
  document.body.appendChild(iframe);
  var retrieved = iframe.contentWindow[native];
  document.body.removeChild(iframe);
  return retrieved;
}

window.escape = retrieveNative('escape');
like image 140
Alsciende Avatar answered Nov 19 '22 19:11

Alsciende


Throw that plugin away because you don't know what evil lurks in there. If you can't do that, then the most optimal solution is to put up a var keyword before escape so it doesn't leak to the global scope and stays within the plugin function.

$.fn.naughtyJQueryPlugin = function() {
    var escape = function() { .. };
};

If you can't modify the plugin source, then wrap code around the plugin to hold on to a reference to the original escape, that you can fix later.

var origEscape = escape;

$.fn.naughtyJQueryPlugin = function() {
    ...
};

escape = origEscape;


Thanks to @Tim pointing out, here's a more robust technique if you can wrap around the plugin source:

(function(escape) {
    $.fn.naughtyJQueryPlugin = function() {
        // any change to escape (not window.escape) will affect the parameter
        // we passed in the outer function to which we have a reference 
        // through a closure.
        // This avoids manipulating the plugin's source, and still have both
        // versions intact.
    };
})(escape); // pass the global escape as a parameter

// should call the global escape
escape("hello");

// when plugin is called, overridden escape should be called
$("div").naughtyJQueryPlugin("message");

See example here. Both versions should co-exist peacefully.

like image 20
Anurag Avatar answered Nov 19 '22 19:11

Anurag