2016-02-11 45 views
0

我有一個HTML頁面鏈接, 如何在JavaScript中打印頁面? 我嘗試做:如何通過js中的鏈接打印HTML頁面?

var printContent = url; 
var windowUrl = 'about:blank'; 
var uniqueName = new Date(); 
var windowName = 'Print' + uniqueName.getTime(); 
var printWindow = window.open("", "_blank"); 

printWindow.document.write(printContent); 
printWindow.focus(); 
printWindow.print(); 
printWindow.close(); 

window.open(location); 

但它打印網址,而不是網頁。 我能做什麼?請幫忙! 謝謝!

+0

我想你需要一些時間來頁面加載,然後打印電話。 Justa猜想可能會試一試 – joyBlanks

+0

不是空白的窗口內容會在稍後提供'printWindow.document.write(printContent);'@BhojendraNepal – joyBlanks

+0

您需要使用XHR請求鏈接,等待響應,然後將其打印爲HTML – MysterX

回答

1

試試這個。刪除打開新窗口的行。我在下面的代碼中進行了評論。你需要爲此查詢jquery。

$(document).ready(function() { 
      $.get('http://example.com', function(data) {     
       var printContent = data; 
       var windowUrl = 'about:blank'; 
        var uniqueName = new Date(); 
        var windowName = 'Print' + uniqueName.getTime(); 
        var printWindow = window.open("", "_blank"); 

        printWindow.document.write(printContent); 
        printWindow.focus(); 
        printWindow.print(); 
        printWindow.close(); 

        //window.open(location); 
        return; 

      }); 
     }); 
+0

謝謝!但他給我的空白頁:(,我必須寫而不是'http://example.com'?我的網址? – Nom

+0

你的網頁有什麼內容。這個頁面是否有權限讀取數據? – PHPExpert

+0

關於你的網址,如果它來自同一個域,那麼它可能會工作(不確定),但如果它來自另一個域,那麼你會得到跨域攔截的錯誤。所以要確保你將使用的任何URL,它有數據,並且也可以訪問 – PHPExpert