在Android设备上使用window.print()或替代方案

时间:2014-10-31 22:12:51

标签: javascript android google-chrome chrome-for-android

在Android设备上(我测试过Nexus 5,Nexus 10,Galaxy S4和Galaxy Tab 3),JavaScript中的window.print()命令无法执行任何操作。据我所知,它甚至没有注册错误。

我知道大多数(如果不是全部)这些浏览器都可以打印,因为您可以使用移动Chrome浏览器的菜单选择" print"。

为什么没有window.print()触发您期望的行为(打开客户端打印菜单)?是否有替代window.print()的Android?

7 个答案:

答案 0 :(得分:5)

Documentation清楚地说明了这一点,“ iOS上支持该命令,Windows上支持Chrome,Mac上支持Chrome。在Android上不支持此功能。

Android手机尚未支持打印,因此window.print()无效。这意味着您需要使用第三方应用程序进行打印。您可以在article中找到一些替代方案。

答案 1 :(得分:3)

使用Google Cloud Print(GCP) - 无需应用。用户必须通过GCP设置打印机。

此示例使用GCP gadget

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Print</title>
    </head>
    <body>
        <div>
            <p>On android devices (I have tested Nexus 5, Nexus 10, Galaxy S4 and Galaxy Tab 3) the window.print() command in javascript doesn't do anything, as far as I can tell it doesn't even register an error.</p>
            <p>I know for a fact that most if not all of these browsers can print because you can use mobile chromes menu to choose "print".  My questions is, why doesn't window.print() trigger the behavior you would expect (opening the clients print menu).
            And is there an android alternative to window.print()?</p>
        </div>

        <div id="gcpPrint"></div>

        <script src="https://www.google.com/cloudprint/client/cpgadget.js">
        </script>

        <script>
            var gadget = new cloudprint.Gadget();
            gadget.setPrintButton(cloudprint.Gadget.createDefaultPrintButton("gcpPrint"));
            gadget.setPrintDocument("text/html", "Print", document.documentElement.innerHTML);
        </script>
    </body>
</html>

答案 2 :(得分:3)

我正在研究一个类似的问题,并提出了这个解决方案:

$(document).ready(function($) {
  var ua = navigator.userAgent.toLowerCase();
  var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");

  $('button.print').click(function(e) {
    e.preventDefault();
    if (isAndroid) {
      // https://developers.google.com/cloud-print/docs/gadget
      var gadget = new cloudprint.Gadget();
      gadget.setPrintDocument("url", $('title').html(), window.location.href, "utf-8");
      gadget.openPrintDialog();
    } else {
      window.print();
    }
    return false;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="print">Print this page</button>

我没有时间检查这是否有效,我目前没有安卓设备。我希望对此有一些反馈; - )

答案 3 :(得分:0)

我认为默认情况下,设备上禁用了直接print()方法。我没有看到这么多手机或其他配备打印机的Android设备,但是通过USB它当然应该是可能的。

相反,建议将内容/页面保存为pdf并通过某些云打印服务进行打印。

答案 4 :(得分:0)

目前,window.print()功能在我的Android 5.0.1设备上完美运行,包括Chrome和默认浏览器。

答案 5 :(得分:0)

现在,window.print()正在使用Android设备。

答案 6 :(得分:-1)

在手机中下载adobe acrobat,然后可以在移动设备中使用windows.print()。