【问题标题】:iOS Safari non-blocking window.printiOS Safari 非阻塞 window.print
【发布时间】:2017-02-14 10:45:59
【问题描述】:

我在 JavaScript 中的页面打印存在特定问题。我需要在删除所有脚本的另一个选项卡上打开我的页面(这种方式:$(document).get(0).documentElement.innerHTML.replace(/<script[^>]+>.*?<\/script>/gi, ''),然后在新选项卡中调用window.print(),然后关闭它。

这是因为脚本中的错误会导致打印出现问题。负责整个打印的代码:

var w = window.open();
w.document.write(
  $(document).get(0).documentElement.innerHTML.replace(/<script[^>]+>.*?<\/script>/gi,'')
);
w.document.close();

var loadingImagesInterval = setInterval(function() {
  var imgs = w.document.querySelectorAll('img');
  for (var i = 0; i < imgs.length; i++) {
    if (!imgs[i].complete) return;
  }

  clearInterval(loadingImagesInterval);

  w.focus();
  w.print();
  w.close();
}, 100);

基本上,问题在于,在 iOS 上,w.print() 似乎不会阻止代码执行,直到在打印视图中确认/取消,然后立即调用 w.close()。所有其他浏览器都可以正常工作:Mac Chrome、Mac Safari、IE11、Mac Firefox。一切都好。只是不是 iOS Safari。

我尝试了这段代码,但效果不佳:

w.matchMedia('print').addListener(function(mql) {
  if (!mql.matches) {
    w.close();
  }
})

有没有更好的方法来处理我的问题?

【问题讨论】:

  • 我仍然坚持这一点。你有想过这个吗?

标签: javascript mobile-safari


【解决方案1】:

编辑:iOS 12.2 版在从主屏幕打开页面时引入了“完成”按钮,因此不需要如下所述的关闭按钮。只有 12.0 及更低版本才需要。

我通过以下方式解决了这个问题:

  • 检测 Safari;
  • 添加打印和关闭按钮并隐藏它们以进行打印;
  • 避免使用write(),因为它会打开一个新页面,并且关闭按钮不会让用户返回上一页。

警告:

  • 可能必须在 Safari 的设置中停用弹出窗口阻止程序,以防止出现“此网站已被阻止自动打印”的警报。
// detect Safari
if (navigator.userAgent.indexOf("Safari") !== -1) {
  // make print button
  const print_button = document.createElement('button');
  const print_button_text = document.createTextNode("Print");
  print_button.appendChild(print_button_text);
  print_button.addEventListener(
    "click",
    function() {
      // hide the buttons before printing
      print_button.style.display = 'none';
      close_button.style.display = 'none';
      newWindow.print();
      // delay reappearing of the buttons to prevent them from showing on the print
      setTimeout(() => {
        print_button.style.display = 'block';
        close_button.style.display = 'block';
      }, 2000);
    },
    false
  );
  // make close button
  const close_button = document.createElement('button');
  const close_button_text = document.createTextNode('Close');
  close_button.appendChild(close_button_text);
  close_button.addEventListener(
    "click",
    function() {
      newWindow.close();
    },
    false
  );
  newWindow.document.body.appendChild(print_button);
  newWindow.document.body.appendChild(close_button);
};

然后我添加了我想要打印的内容。我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 2015-05-02
    相关资源
    最近更新 更多