iOS Safari非阻塞window.print

Tom*_*rek 7 javascript mobile-safari

我在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);
Run Code Online (Sandbox Code Playgroud)

基本上,问题是,在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();
  }
})
Run Code Online (Sandbox Code Playgroud)

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

ski*_*nda 2

编辑: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);
};
Run Code Online (Sandbox Code Playgroud)

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