tampermonkey 使用原生JS打印节点 不使用 jspdf 和 html2canvas等第三方库,带上原始节点的样式
时间: 2024-01-24 22:18:37 浏览: 30
要在 Tampermonkey 中使用原生 JS 打印节点并带上原始节点的样式,可以使用 `window.print()` 方法结合 `@media print` 媒体查询来实现。
以下是一个示例代码:
```javascript
// ==UserScript==
// @name Print Element with Styles Tampermonkey Script
// @match https://example.com/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
function printElement(el) {
var printWindow = window.open('', 'PrintWindow');
printWindow.document.write('<html><head><title>' + document.title + '</title>');
printWindow.document.write('<style>@media print { body { visibility: hidden; } }</style>');
printWindow.document.write('</head><body>');
printWindow.document.write(el.outerHTML);
printWindow.document.write('</body></html>');
printWindow.document.close();
setTimeout(function() {
printWindow.print();
printWindow.close();
}, 500);
}
// Example usage:
var myElement = document.getElementById('myElementId');
printElement(myElement);
})();
```
这段代码会在 Tampermonkey 脚本运行时定义一个 `printElement` 函数,接受一个 DOM 元素作为参数,并将该元素的 HTML 内容写入一个新的打印窗口中,同时在 `@media print` 媒体查询中隐藏页面主体内容,以确保只打印指定的元素。在打印窗口准备好后,等待 500 毫秒(或更长时间)以确保所有的样式都已加载完成,然后调用 `print()` 方法打印该窗口,并在打印完成后关闭该窗口。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)