1

I am trying to copy the value of 'longlat' to clipboard automatically without having to press a button in HTML. I have tried clipboards and Clipboard.JS but have not been able to find a solution to doing this without HTML or getting some error.

 const clipboardy = (...args) => import('clipboardy').then(({default: clipboardy}) => clipboardy(...args));
  const puppeteer = require("puppeteer");
 
  const url = "https://www.google.com/";
  
  async function StartScraping() {
    await puppeteer
      .launch({
        headless: false,
      })
      .then(async (browser) => {
        const page = await browser.newPage();
  
        await page.setViewport({
          width: 2000,
          height: 800,
        });
  
        page.on("response", async (response) => {
  
         
          if (response.url().includes("Start")) {
            const location = await response.text() 
            let intlong = location.indexOf("Example:")
            const longlat = location.substring(intlong , intlong + 46)
           
            console.log(longlat);



            copyData(longlat)
            
            }
  
        });
  
        await page.goto(url, {
          waitUntil: "load",
          timeout: 0,
        });
      });
  }

function copyData(data1) {
  
  clipboard.writeSync(data1)
}



  StartScraping();

Nicky
  • 57
  • 1
  • 1
  • 7

1 Answers1

2

You can use javascript's navigator to copy to clipboard any text, like below

navigator.clipboard.writeText("String to be copied!");

create a function to copy and use it.

function copy(text) {
  /* Copy the text inside the text field */
  navigator.clipboard.writeText(text);
  
  /* Alert the copied text */
  alert("Copied the text: " + text);
}

copy("Hello, I'll be copied!");
Abhijeet Vadera
  • 491
  • 2
  • 7
  • I have added it to my code but it gives me the error ' (node:6656) UnhandledPromiseRejectionWarning: ReferenceError: navigator is not defined ' and '(node:6656) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 4)' Do you know howto fix – Nicky Mar 16 '22 at 06:33