在IOS的Safari中,打印和关闭JavaScript功能似乎不像其他浏览器那样起作用。如果单独调用window.print()
似乎可以正常工作。但是,如果您随后立即调用window.close()
,则尽管打印预览窗口仍处于打开状态,但它似乎关闭了窗口并打印了预览,它不等待打印预览完成或取消以关闭窗口,而只是关闭了窗口立即打开。
我创建了一个用于打印表格的按钮。它将在新窗口中打开表格,并打开打印功能,并稍等片刻,以使浏览器可以打开页面并呈现表格。打印完成后,应该关闭窗口。
提示:如果您拥有Mac和Xcode,则可以通过启动服务器python -m SimpleHTTPServer 8000
来打开iPhone模拟器并使用python访问localhost。要访问模拟器,请依次打开Xcode和Xcode> Open Developer Tools> Simulator
这是代码:
<!DOCTYPE html>
<html>
<head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body>
<table class="table">
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Yoshi Tannamuri</td>
<td>Canada</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
</table>
<button onclick="myPrintFunction()">Click me</button>
<script>
function myPrintFunction() {
let divToPrint = document.getElementsByClassName("table")[0];
if (typeof divToPrint !== 'undefined') {
let newWin = window.open();
newWin.document.write('<h1>PRINT FRIENDLY</h1>');
newWin.document.write(divToPrint.outerHTML);
newWin.document.close();
newWin.focus();
setTimeout(()=>{
newWin.print();
newWin.close();
}, 1000);
} else {
alert('NO EVENTS TO PRINT!');
}
}
</script>
</body>
</html>
最佳答案
我避免使用write(),因为它删除了DOM。然后,我同时添加了打印和关闭按钮。为了避免渲染这些图像,我让它们消失并在10秒后重新出现。
// 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';
}, 10000);
},
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);
};
关于javascript - window.print()和window.close()函数Safari IOS在不等待打印预览的情况下关闭窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53916266/