js解決pdf使用iframe打印報跨域錯誤問題的方法示例
報錯如下:
Uncaught DOMException: Failed to read a named property ‘print’ from ‘Window’: Blocked a frame with origin “https://xxxx.com” from accessing a cross-origin frame.
at iframe.onload (:10:26)
解決方法:
把 pdf 轉 blob 二進制數(shù)據(jù), 通過 createObjectURL 生成本地對象 url, 在創(chuàng)建 iframe 調用打印接口
printPDF()
function printPDF() {
fetch('https://xxxxx.com/xxxx.pdf')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.blob(); // 獲取二進制數(shù)據(jù)
})
.then(blobData => {
// 替換這里的 PDF_URL 為你要打印的 PDF 文件鏈接
const PDF_URL = URL.createObjectURL(blobData);
// 創(chuàng)建一個隱藏的 iframe 元素
const iframe = document.createElement('iframe');
// 等待 PDF 加載完成后進行打印
iframe.onload = function() {
iframe.contentWindow.print();
};
iframe.style.display = 'none';
iframe.src = PDF_URL;
// 將 iframe 添加到頁面中
document.body.appendChild(iframe);
})
}附:iframe打印pdf跨域問題,使用blob流轉為同源
<iframe :src="pdfUrl2" width="100%" height="700px" id="printMe" hidden></iframe>
<iframe :src="pdfUrl" width="100%" height="700px"></iframe>
import axios from 'axios'
axios({
method: 'get',
url: this.pdfUrl,
responseType: 'blob'
})
.then(response => {
this.pdfUrl2= window.URL.createObjectURL(response.data)
setTimeout(() => {
document.getElementById('printMe').contentWindow.print();
},2000)
})
.catch(function(error) {
console.log(error)
})總結
到此這篇關于js解決pdf使用iframe打印報跨域錯誤問題的文章就介紹到這了,更多相關js pdf用iframe打印報跨域錯誤內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
使用JS獲取input file的路徑C:\fakepath\問題及解決方法
這篇文章主要介紹了使用JS獲取input file的路徑C:\fakepath\問題及解決方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-01-01
關于Object.entries()方法的使用和實現(xiàn)方式
這篇文章主要介紹了關于Object.entries()方法的使用和實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02
使用pdf-lib.js實現(xiàn)拼接兩個pdf文件并添加水印
這篇文章主要為大家詳細介紹了如何使用pdf-lib.js實現(xiàn)拼接兩個pdf文件并添加水印,文中的示例代碼講解詳細,感興趣的小伙伴可以了解下2024-11-11
js的form表單提交url傳參數(shù)(包含+等特殊字符)的兩種解決方法
下面小編就為大家?guī)硪黄猨s的form表單提交url傳參數(shù)(包含+等特殊字符)的兩種解決方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-05-05

