【发布时间】:2018-09-23 00:43:59
【问题描述】:
我试图弄清楚如何在单击按钮时从另一个网页链接打印图像。
我知道window.print(),但我如何指定要从中打印图像的其他链接?
【问题讨论】:
标签: javascript html css user-interface frontend
我试图弄清楚如何在单击按钮时从另一个网页链接打印图像。
我知道window.print(),但我如何指定要从中打印图像的其他链接?
【问题讨论】:
标签: javascript html css user-interface frontend
如果您要打印的页面与 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 的内容来自您的域,并且不会在您尝试打印时打嗝。
但是,如果您尝试在前端执行此操作,这只会将问题推后一步,因为同源策略也不会让您以这种方式从另一个域中抓取内容。但是数据抓取的同源策略相当于用棉线将公牛绑起来——它并没有真正阻碍你——所以这个障碍很容易绕过。您可以编写自己的后端脚本(使用 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 打印的内容可能与您预期的完全不同。
【讨论】: