iframe调用contentWindow.print()如何判断是否有值
时间: 2024-03-09 14:45:44 浏览: 45
如果要判断 `iframe` 中是否有可打印内容,可以通过以下方式:
1. 判断 `iframe` 是否有子节点,如果没有,则视为没有可打印内容,否则视为有可打印内容。例如:
```javascript
const iframe = document.querySelector('iframe');
if (iframe && iframe.childNodes.length > 0) {
iframe.contentWindow.print();
} else {
console.log('No content to print');
}
```
2. 判断 `iframe` 中的页面是否加载完成,如果没有,则视为没有可打印内容,否则视为有可打印内容。例如:
```javascript
const iframe = document.querySelector('iframe');
iframe.onload = function() {
if (iframe.contentWindow.document.readyState === 'complete') {
iframe.contentWindow.print();
} else {
console.log('No content to print');
}
}
```
需要注意的是,由于跨域访问的限制,如果 `iframe` 的内容来自不同的域名,访问 `contentWindow` 时可能会抛出安全异常,此时无法打印 `iframe` 的内容。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)