如果我有类似的东西
alert = 0;
Run Code Online (Sandbox Code Playgroud)
在另一个脚本中.
这是在另一个脚本中,我的代码无法在该脚本之前加载.
如何alert在脚本中调用原始方法?
jfr*_*d00 15
在覆盖原件之前alert,请保存它.
var origAlert = alert;
alert = 0;
origAlert("foo");
Run Code Online (Sandbox Code Playgroud)
演示:http://jsfiddle.net/jfriend00/tnNE7/
如果您无法保存原始值,我知道的唯一其他方式是访问iframe.这是一个例子:
alert = 0;
var iframe = document.createElement("iframe");
iframe.height = 0;
iframe.width = 0;
document.body.appendChild(iframe);
iframe.contentWindow.alert.call(window, "foo");?
Run Code Online (Sandbox Code Playgroud)
工作示例:http://jsfiddle.net/jfriend00/waMEV/
我没有在所有浏览器中尝试这个,但它适用于Chrome,IE和Firefox,我认为它应该适用于其他浏览器.
好吧,我是第一个承认这是一个丑陋的答案,但它似乎工作:
alert = 0;
var win = window.open(),
method = win.alert;
win.close();
method.call(window, "my message");
Run Code Online (Sandbox Code Playgroud)
在这里小提琴 基本上,您创建一个新窗口实例并窃取其alert方法.缺点是你实际上必须打开一个新的浏览器窗口,虽然是短暂的.我怀疑这实际上是解决您问题的实际方法 - 取决于您正在尝试使用的其他网站,以及您关心解决方案对最终用户的看法.
编辑:这是上面的答案和jfriend00的答案的组合,它解决了"打开一个新窗口"的问题.我认为这是一个更好的选择,因为a)当你需要调用方法时它不依赖于iframe仍然在DOM中,并且b)它应该可以推广到任何window方法,jfriend00的答案可能不是'吨.
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");
Run Code Online (Sandbox Code Playgroud)