在页面到达window.print()之前执行函数

joe*_*joe 8 javascript

我有一个调用window.print()的页面; 在页面的底部.我无法访问window.print(); 它由服务器生成,我无法触摸它.基本上是因为IE我需要在打印对话框出现之前执行一些javascript,但是在页面加载之后.我不能这样做因为它一旦到达window.print(); 出现打印对话框.我仍然需要打印,但首先我需要运行myFunction()然后我可以使用window.print();

<html><head></head><body></body><!--no access from here--><script>window.print();</script></html>
Run Code Online (Sandbox Code Playgroud)

Jos*_*ola 21

你应该能够像这样覆盖它......

var _print = window.print;
window.print = function() {
  alert("Hi!");
  // do stuff
  _print();
}
Run Code Online (Sandbox Code Playgroud)

  • 在Chrome 8和其他浏览器中,请注意使用文件·打印或以其他方式从浏览器chrome(不是页面脚本)执行打印不会调用`window.print`,并且不会执行此代码.测试用例:http://dl.dropbox.com/u/105727/web/print_function.html (8认同)
  • @艾伦H。刚刚在 Chrome 中使用“Ctrl+P”进行了测试,我确认它不起作用。 (2认同)

And*_*y E 9

"基本上因为IE我需要..."

如果您只需要IE支持,请参阅onbeforeprint事件.

window.onbeforeprint = function () {
    // some code    
}
Run Code Online (Sandbox Code Playgroud)

这里的好处是代码不会在不支持onbeforeprint的浏览器中运行,而onbeforeprint几乎是除了IE之外的所有浏览器.