如何在nodejs中使用Puppeteer从浏览器剪贴板复制文本 [英] How to copy text from browser clipboard using Puppeteer in nodejs

查看:31
本文介绍了如何在nodejs中使用Puppeteer从浏览器剪贴板复制文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 nodejs 中使用 Puppeteer 从浏览器剪贴板复制内容.我正在尝试复制页面呈现后的内容.这是通过波纹管代码实现的,但无法获取内容.

Is a there a way where I can copy content from browser clipboard using Puppeteer in nodejs. I am trying to copy content post the page is rendered. This is being achieved by the bellow code but unable to get the content.

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');

推荐答案

从输入框复制

您可以评估以下代码段以从任何输入元素复制数据.

Copy from input box

You can evaluate the following snippet to copy data from any input element.

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");
});

现在结果应该包含从输入框中复制的文本.

now result should contain the text copied from the input box.

您可以评估来自这个答案的片段.

You can evaluate the snippet from 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
});

它将创建一个输入元素,将您提供的文本设置为值,然后从该元素复制数据,最后在使用后将其删除.

It will create a input element, set your provided text as value and then copy the data from that element, finally remove it after usage.

这篇关于如何在nodejs中使用Puppeteer从浏览器剪贴板复制文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆