Using puppeteer, I want to add some text to clipboard and then paste to an element
To add text to the clipboard and then paste it into an element using Puppeteer, you can use the following code:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
// Go to your desired webpage
await page.goto('https://example.com');
// Add text to the clipboard
await page.evaluate(() => {
const text = 'Hello, world!';
navigator.clipboard.writeText(text);
});
// Focus on the target element where you want to paste the text
await page.focus('#target-element');
// Paste the text from the clipboard
await page.keyboard.down('Control');
await page.keyboard.press('KeyV');
await page.keyboard.up('Control');
// Wait for a while to see the pasted text
await page.waitForTimeout(2000);
await browser.close();
})();
In this code, we use the navigator.clipboard.writeText()
function to add the desired text to the clipboard. Then, we use Puppeteer's keyboard functions to simulate the keypress events for pasting the text into the target element. Finally, we wait for a while to see the pasted text before closing the browser.
Make sure to replace 'https://example.com'
with the URL of the webpage you want to interact with, and 'target-element'
with the selector of the element where you want to paste the text.
I want to pass text to page.evaluate
To pass text to the page.evaluate()
function in Puppeteer, you can use the following code:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
// Go to your desired webpage
await page.goto('https://example.com');
// Text to be passed to page.evaluate()
const text = 'Hello, world!';
// Pass the text to page.evaluate()
await page.evaluate((text) => {
// Use the passed text in your evaluation logic
console.log(text);
}, text);
await browser.close();
})();
In this code, we define the text
variable with the desired text that you want to pass to the page.evaluate()
function. Then, inside the page.evaluate()
function, you can access this text using the text
parameter.
Make sure to replace 'https://example.com'
with the URL of the webpage you want to interact with. You can modify the code inside the page.evaluate()
function to perform any desired logic using the passed text.