如何覆盖标准浏览器打印并默认打印iframe [英] How to override standard browser print and print an iframe by default

查看:179
本文介绍了如何覆盖标准浏览器打印并默认打印iframe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有iframe的文档类型页面。我试图重写标准浏览器打印(Ctrl + p)来打印iframe的内容。

I have a documentation type page with an iframe inside. I'm trying to override standard browser print (Ctrl + p) to print contents of an iframe only.

我知道如何使用javascript打印iframe内容:

I know how to print an iframe content using javascript:

window.frames['webcontent'].focus();
window.frames['webcontent'].print();

我知道如何在打印前运行javascript,例如如下所述:检查用户何时选择使用javascript打印

I know how to do run javascript before printing e.g. as described here: Check for when a user has selected to print using javascript

任何提示?

谢谢

Thanks

推荐答案

这是不可能的(使用Javascript)。在现代浏览器中有一些用户启动的打印事件的实验支持,但那些是不可取消(简单事件),因此即使您插入自定义代码来打印相关框架,整个页面仍会打印。

It's not possible (using Javascript). There is some experimental support for user-initiated print events in modern browsers, but those are not cancelable ("simple events") so the entire page will still print even if you interject custom code to print the frame of interest.

鉴于此限制,最好的办法就是给用户提供一个大按钮来激发你的自定义框架打印功能(参见下面的 printContentFrameOnly ,不需要参数就可以触发它),并且希望他们使用按钮代替ctrl-p。

Given this limitation, your best bet is probably to offer users a large button that fires your custom frame printing function (see printContentFrameOnly below, fire it without arguments) and hope that they'll use the button instead of ctrl-p.

如果有可能,那么这就是实现它的方法(基于这个答案):

If it would be possible, this would be the way to do it (based on this answer):

// listener is a function, optionally accepting an event and
// a function that prints the entire page
addPrintEventListener = function (listener) {

    // IE 5.5+ support and HTML5 standard
    if ("onbeforeprint" in window) {
        window.addEventListener('beforeprint', listener);
    }

    // Chrome 9+, Firefox 6+, IE 10+, Opera 12.1+, Safari 5.1+
    else if (window.matchMedia) {
        var mqList = window.matchMedia("print");

        mqList.addListener(function (mql) {
            if (mql.matches) listener();  // no standard event anyway
        }); 
    }

    // Your fallback method, only working for JS initiated printing
    // (but the easiest case because there is no need to cancel)
    else {    
        (function (oldPrint) { 
            window.print = function () {
                listener(undefined, oldPrint);
            }
        })(window.print);
    }
}

printContentFrameOnly = function (event) {
    if (event) event.preventDefault();  // not going to work
    window.frames['webcontent'].focus();
    window.frames['webcontent'].print();
}

addPrintEventListener(printContentFrameOnly);

这篇关于如何覆盖标准浏览器打印并默认打印iframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆