如何在 Chrome 中访问打印窗口的 HTML?

问题描述 投票:0回答:1

我想编写打印网页的代码。 print() 是不够的,因为它只打开浏览器的打印窗口,并没有立即打印。此外,我还对控制打印选项(例如打印为 PDF 或特定尺寸)感兴趣。

于是我在打开打印窗口的情况下打开Chrome的开发者工具,复制保存按钮的js路径,在我要打印的网页中尝试写了如下代码:

print()
document.querySelector("body > print-preview-app").shadowRoot.querySelector("#sidebar").shadowRoot.querySelector("print-preview-button-strip").shadowRoot.querySelector("div > cr-button .action-button")click()

我得到一个错误,因为这个元素没有出现在页面本身上,而是出现在打印窗口中。事实证明,窗口实际上是一个单独的页面(chrome://print/),但它以某种方式嵌入到打印页面中或者看起来与其无关。

我的问题是,在这种情况下如何在窗口上运行JS?

我的问题绝对不同于这个问题。那里的问题是关于插件的,问题是访问 chrome:// 页面,因为它们就是这样,而 Chrome 不允许访问它们。但我正在编写一个常规脚本(不是插件),因此它总是可以访问这些页面。我的问题是打印窗口不是网站页面的一部分,而是单独显示的。

后脚本。 1. 或许也可以直接使用 JS 来进行 Chrome 打印,但目前与我无关。问题是如何访问上面的 HTML 元素。

  1. 我见过类似的问题(像这个)。我没有看到任何答案。
javascript google-chrome pdf dom printing
1个回答
1
投票

很遗憾地告诉你,这是不可能的。 另一方面,您始终可以使用警报 JS 库(如 sweetalert2),然后只需编辑警报 div 的内部 HTML。

首先,在您的 HTML 中包含 sweetalert2 脚本

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
.

然后,编写一个创建弹出窗口的函数

function showAlert(){
  Swal.fire(
  'Good job!',
  'You clicked the button!',
  'success'
)

获取弹出元素并编辑它的 innerHTML

document.getElementsByClassName("swal2-popup")[0].innerHTML = "Write here your HTML for the popup.";

并结束函数

`}`

function showAlert(){
  Swal.fire(
  'Good job!',
  'You clicked the button!',
  'success'
)
document.getElementsByClassName("swal2-popup")[0].innerHTML = "Hello, this is an alert with a <button onclick='alert()'>button</button>.";
}
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<body>
  <p>Hi, this is some inutile text here.
  
  Lorem ipsum dolor sit amet consectetur adipiscing elit praesent, maecenas felis aenean sapien vulputate sed porttitor habitasse auctor, hendrerit eros nibh ligula mollis ornare venenatis. Taciti arcu dapibus aliquam ridiculus nostra posuere velit, facilisi aenean morbi vehicula cursus nullam sapien potenti, tristique pulvinar nulla fames auctor rutrum. Faucibus torquent dui interdum quisque nisi nam maecenas duis, mauris eget class euismod integer curae ultricies, tempor sem felis varius sapien nunc cum.</p><button onclick="showAlert()">SHOW ALERT</button>
</body>

© www.soinside.com 2019 - 2024. All rights reserved.