最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Call native browser function, even after it has been overridden - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Jun 28, 2017 at 20:43 Kara 6,22616 gold badges53 silver badges58 bronze badges asked Aug 4, 2012 at 5:28 DogbertDogbert 222k42 gold badges417 silver badges414 bronze badges 1
  • if it is usefull Javascript confirm dialog can be used to show a message if the yes/no buttons can be ignored. – Ekim Commented Aug 4, 2012 at 6:04
Add a ment  | 

2 Answers 2

Reset to default 16

Before overriding the original alert, save it.

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

Demo: http://jsfiddle/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/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.

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 bo 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");
发布评论

评论列表(0)

  1. 暂无评论