单击按钮,从另一个链接打印表格

时间:2018-09-23 00:44:00

标签: javascript html css user-interface frontend

我试图找出如何在单击按钮时从另一个网页链接打印图像。 我知道leftEnoughRoom,但如何指定要从中打印图像的其他链接?

1 个答案:

答案 0 :(得分:0)

相同域

如果您希望打印的页面与iframe的父目录位于同一域中,则MDN对此的处理方式为good example

您应该创建一个隐藏的iframe,在其中加载页面,打印iframe内容,然后删除iframe。

JavaScript:

function printURL( url ) {
    var frame = document.createElement( "iframe" );
    frame.onload = printFrame;
    frame.style.display = 'none';
    frame.src = url;
    document.body.appendChild(frame);
    return false;
}
function printFrame() {
    this.contentWindow.__container__ = this;
    this.contentWindow.onbeforeunload = closeFrame;
    this.contentWindow.onafterprint = closeFrame;
    this.contentWindow.focus(); // Required for IE
    this.contentWindow.print();
}
function closeFrame () {
    document.body.removeChild(this.__container__);
}

HTML:

<button onclick="printURL('page.html');">Print external page!</button>

跨域

如果您要打印的页面来自其他域,则您的浏览器将引发“同源策略”错误。这是一项安全功能,禁止脚本访问来自不同域的某些数据。

要打印跨域内容,您将需要抓取页面的源并将其加载到iframe中。然后,浏览器将认为iframe的内容来自您的域,并且在您尝试打印时不会打hi。

但是,如果您尝试在前端执行此操作,则只会使问题再退一步,因为同源策略也不允许您以这种方式从另一个域抓取内容。但是,用于数据抓取的相同政策等同于将公牛与棉线绑在一起-它并没有真正让您退缩-因此可以轻松地规避这一障碍。您可以编写自己的后端脚本(使用PHP或您选择的语言)来抓取内容并将其传送到您的页面,或者可以使用许多已经执行此操作的Web服务中的任何一个。 https://multiverso.me/AllOrigins/一样出色,它不需要后端编程,它是免费的,因此在本示例中将使用它。

使用Jquery,上面修改过的printURL函数将是:

function printURL( url ) {
    var jsonUrl = 'http://allorigins.me/get?url=' + encodeURIComponent(url) + '&callback=?';
    // the url / php function that allows content to be scraped from different origins.

    $.getJSON( jsonUrl, function( data ) {
        // get the scraped content in data.content
        var frame = document.createElement( "iframe" ),
        iframedoc = frame.contentDocument || frame.contentWindow.document;
        frame.onload = printFrame;
        frame.style.display = 'none';
        iframedoc.body.html( data.contents );
        document.body.appendChild(frame);
    }
    return false;
}

上面的其他功能将保持不变。

请注意,如果您要打印的页面是使用AJAX调用构建的,或者使用脚本编写了明显的样式,则iframe可能会打印出与您期望的外观完全不同的东西。