Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call native browser function, even after it has been overridden

Tags:

javascript

If I have something like

alert = 0;

in another script.

This is in another script is and my code cannot load before that script.

How can I call the original alert method in my script?

like image 659
Dogbert Avatar asked Aug 04 '12 05:08

Dogbert


2 Answers

Before overriding the original alert, save it.

var origAlert = alert;
alert = 0;
origAlert("foo");

Demo: http://jsfiddle.net/jfriend00/tnNE7/


If you can't save the original value, the only other way I know of to get access to it is in an iframe. Here's an example:

alert = 0;
var iframe = document.createElement("iframe");
iframe.height = 0;
iframe.width = 0;
document.body.appendChild(iframe);
iframe.contentWindow.alert.call(window, "foo");​

Working example: http://jsfiddle.net/jfriend00/waMEV/

I haven't tried this in all browsers, but it works in Chrome, IE and Firefox and I think it should work in other browsers.

like image 169
jfriend00 Avatar answered Oct 16 '22 08:10

jfriend00


Ok, I'm the first to admit this is an ugly answer, but it seems to work:

alert = 0;

var win = window.open(),
    method = win.alert;
win.close();

method.call(window, "my message");

Fiddle here. Essentially, you make a new window instance and steal its alert method. The downside is that you actually have to open a new browser window, albeit briefly. I doubt this is actually a practical solution to your problem - depends what other site you're trying to work with, and how much you care about how your solution looks to the end user.

Edit: This is a combo of the above answer and jfriend00's answer, which solves the "open a new window" problem. I think this is a somewhat better option, as a) it doesn't rely on the iframe still being in the DOM when you need to call the method, and b) it should be generalizable to any window method, which jfriend00's answer probably isn't.

alert = 0;

// make a new window instance in an iframe
var iframe = document.createElement("iframe");
iframe.height = iframe.width = 0;
document.body.appendChild(iframe);
// steal the method
var method = iframe.contentWindow.alert;
// remove the evidence
document.body.removeChild(iframe);

// now use the method for your own purposes
function myAlert(message) {
    method.call(window, message);
}
myAlert("foo");
like image 28
nrabinowitz Avatar answered Oct 16 '22 08:10

nrabinowitz