有没有一种方法可以让我在nodejs中使用Puppeteer从浏览器剪贴板复制内容。我正在尝试复制页面呈现后的内容。这是通过以下代码实现的,但无法获取内容。
await page.keyboard.down('ControlLeft');
await page.keyboard.press('KeyA');
await page.keyboard.up('ControlLeft');
await page.keyboard.down('ControlLeft');
await page.keyboard.press('KeyC');
await page.keyboard.up('ControlLeft');
最佳答案
从输入框复制
您可以评估以下代码片段以从任何输入元素复制数据。
function copyText(selector) {
var copyText = document.querySelector(selector);
copyText.select();
document.execCommand("Copy");
return copyText.value;
}
用法:
const result = await page.evaluate(() => {
function copyText(selector) {
var copyText = document.querySelector(selector);
copyText.select();
document.execCommand("Copy");
return copyText.value;
}
return copyText("#foo");
});
现在结果应该包含从输入框中复制的文本。
将任何内容复制到剪贴板
您可以评估 this answer 中的代码片段。
const result = await page.evaluate(() => {
function copy(text) {
var input = document.createElement('input');
input.setAttribute('value', text);
document.body.appendChild(input);
input.select();
document.execCommand('copy');
document.body.removeChild(input)
}
return copy(document.body.innerHTML); // copy whatever want to copy
});
它将创建一个输入元素,将您提供的文本设置为值,然后从该元素复制数据,最后在使用后将其删除。
关于node.js - 如何在nodejs中使用Puppeteer从浏览器剪贴板复制文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49131516/