![](/img/trans.png)
[英]window.open(url, '_blank'); not working on iMac/Safari
[英]window.open(url).print() not working in Safari
我在Safari瀏覽器中打印時遇到問題。 當我使用window.open(url)
並嘗試打印這個新打開的URL時,它會嘗試打印一個空白頁面。
正如其他幾個網站所建議的那樣,我試圖將延遲設置為3000毫秒。 喜歡,
window.open(url)
setTimeout(print, 3000);
這會嘗試打印上一個窗口而不打開新選項卡。
我在打印之前嘗試過使用window.focus()
。 它沒有幫助。
首先,在setTimeout中傳遞的Window
對象是原始頁面中的那個,所以你應該做類似的事情
var popup = window.open(url);
popup.onload= function(){
// this now refers to `popup`
this.print()
}
但是既然你提到了Safari的問題,我會注意到這似乎只適用於這個瀏覽器中的普通文檔頁面(至少對於HTML文件)。
對於像data:image/...
這樣的文檔, window.open()
返回的Window對象沒有任何屬性(至少在10.9版本的Safari 9.1中,沒有在其他版本中嘗試過),因此你可以' t調用popup.print()
方法。
一種方法是創建自己的頁面,例如為圖像添加一個帶有所需URL的<img>
標簽作為src
。 這取決於你打算打印什么。
var url = 'data:image/png;base64,...';
// you have to keep a reference of the new Window
var popup = window.open(url);
var tryToPrint = function() {
// we have access to the window methods
if (popup.print) {
// call directly its print method
popup.print()
} else {
// close this one
popup.close();
// open a new blank one
popup = window.open('');
// create an image
var img = popup.document.createElement('img');
// reproduce default Safari's styles
img.setAttribute('style', '-webkit-user-select:none; display:block; margin:auto;');
// once the image has loaded, we can print the page
img.onload = function() {
popup.print()
};
popup.document.body.appendChild(img);
img.src = url;
}
};
// unfortunately, we can't even listen to the load event of the bugged popup
// so come back to an ugly timeout...
setTimeout(tryToPrint, 200);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.