iframe print
时间: 2023-11-06 13:07:45 浏览: 14
iframe print是一种在网页中使用iframe标签来打印指定区域的方法。通过使用此方法,可以选择页面中的特定区域进行打印,而不是整个页面。与普通的print()函数不同的是,使用iframe print可以在取消打印后完整保留当前访问页面的内容。在JavaScript中,可以使用相应的代码来实现iframe print功能。
相关问题
vue-print-nb iframe打印
好的,关于vue-print-nb中使用iframe打印的问题,可以参考以下步骤:
1. 安装vue-print-nb插件:
```
npm install vue-print-nb --save
```
2. 在需要打印的组件中引入vue-print-nb插件:
```javascript
import Print from 'vue-print-nb'
export default {
...
components: {Print},
...
}
```
3. 在需要打印的地方添加一个按钮或者其他触发事件:
```html
<template>
...
<button @click="print">打印</button>
...
</template>
```
4. 在需要打印的方法中使用vue-print-nb提供的方法:
```javascript
export default {
...
methods: {
print () {
// 打印的内容
let printContent = this.$refs.printContent
this.$print(printContent)
}
}
...
}
```
5. 在需要打印的地方添加一个`ref`属性:
```html
<template>
...
<div ref="printContent">
<!-- 打印的内容 -->
</div>
...
</template>
```
6. 在需要打印的组件中添加一个`iframe`元素:
```html
<template>
...
<iframe id="print" frameborder="0" width="0" height="0"></iframe>
...
</template>
```
这样就可以使用vue-print-nb插件中的`$print`方法来进行iframe打印了。
iframe调用contentWindow.print()空白
如果在 `iframe` 中调用 `contentWindow.print()` 方法出现空白页,可能有以下几个原因:
1. `iframe` 中的页面加载完成之前就调用了 `contentWindow.print()` 方法,此时打印的是空白页。可以通过在 `window.onload` 事件中调用 `contentWindow.print()` 方法来避免这个问题。
```javascript
const iframe = document.querySelector('iframe');
iframe.onload = function() {
iframe.contentWindow.print();
}
```
2. `iframe` 中的页面中包含了未加载完成的资源,例如图片、样式等,这些资源加载完成之前打印的也是空白页。可以通过在 `window.onload` 事件中等待所有资源加载完成之后再调用 `contentWindow.print()` 方法来避免这个问题。
```javascript
const iframe = document.querySelector('iframe');
iframe.onload = function() {
const checkPrint = setInterval(function() {
if (iframe.contentWindow.document.readyState === 'complete') {
clearInterval(checkPrint);
iframe.contentWindow.print();
}
}, 100);
}
```
3. `iframe` 中的页面中存在跨域资源,例如图片等,这些资源无法被 `iframe` 访问,因此打印的是空白页。可以通过将跨域资源放在同一域名下,或者在 `iframe` 中使用 `postMessage` 等方式与父页面通信来避免这个问题。
需要注意的是,由于跨域访问的限制,如果 `iframe` 的内容来自不同的域名,访问 `contentWindow` 时可能会抛出安全异常,此时无法打印 `iframe` 的内容。