English 中文(简体)
具体目标Clos 在Popppeteer使用伐木承诺
原标题:TargetCloseError when using promises in Puppeteer for logging

I m new to Java and to the Puppeteer Library. 我知道什么是同yn一样的方案拟订工作,我与它一道在 Java语中玩.,但当我试图用Pppeteer加以利用时,我会发现错误。

This is my index.js file:

(async () => {
  const browser = await puppeteer.launch({
    headless: false,
  });

  // Disable Facebook notifications
  const context = await browser.defaultBrowserContext();
  await context.overridePermissions( https://www.facebook.com , [ geolocation ,  notifications ]);

  const page = await browser.newPage();
  const logger = await myLog.logger;

  console.log( About to use function. );
  await utils.webAction(
    logger,  Enter Facebook ,
    (() => (page.goto(constants.linkHomepage, {waitUntil: [ domcontentloaded ,  networkidle2 ]})))
  );
  console.log( Content loaded );

  // User Login
  await utils.webAction(
    logger,  Wait for loginEmail element ,
    (() => (page.waitForSelector(constants.cssLoginEmail, {visible: true}))),
  );
  // Using a fake (incorrect) xpath to trigger the "catch" block
  await utils.webAction(
    logger,  Enter user email using incorrect xpath , utils.webType,
    page, "Fake user", "fake xpath/css"  // Arguments of `webType`
  );
})();

<代码>utils.js file:

module.exports = {
  webAction: function (logger, msg, func, ...args)
  {
    return new Promise((resolve) => {
      let actionMessage, actionLevel;
      try
      {
        func(...args);
        actionMessage = msg;
        actionLevel =  info ;
      }
      catch (error)
      {
        actionMessage = "Error while executing " + msg + " function.
---
" + error.message + "
---";
        actionLevel =  error ;
      }
      finally
      {
        logger.log({
          level: actionLevel,
          message: actionMessage
        })
      }
      console.log( Inside resolve Promise );
      resolve( Fullfilment value of Promise );
      console.log( Last line if resolve body );
    })
  },

  // Type into input field
  webType: function (page, text, xpath)
  {
    page.type(
      xpath, text,
      {delay: getRandomIntInRange(constants.minSpeed, constants.maxSpeed)}
    );
  },

};

我创设了功能,因为我希望该守则能够看清更清洁的情况,并追踪方案坠毁之处(我对实现这一目标的其他途径开放)。

错误是:

About to use function.
info: Enter Facebook {"timestamp":"2024-01-18 16:43:59"}
Inside resolve Promise
Last line if resolve body
Content loaded
info: Wait for loginEmail element {"timestamp":"2024-01-18 16:43:59"}
Inside resolve Promise
Last line if resolve body
info: Enter user email using incorrect xpath {"timestamp":"2024-01-18 16:43:59"}
Inside resolve Promise
Last line if resolve body
/home/user/Projects/Javascript/Facebook/node_modules/puppeteer-core/lib/cjs/puppeteer/common/CallbackRegistry.js:85
            this._reject(callback, new Errors_js_1.TargetCloseError( Target closed ));
TargetCloseError: Protocol error (Runtime.callFunctionOn): Target closed
    at CallbackRegistry.clear (/home/user/Projects/Javascript/Facebook/node_modules/puppeteer-core/lib/cjs/puppeteer/common/CallbackRegistry.js:85:36)
    at CdpCDPSession._onClosed (/home/user/Projects/Javascript/Facebook/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/CDPSession.js:113:25)
    at Connection.onMessage (/home/user/Projects/Javascript/Facebook/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Connection.js:132:25)
    at WebSocket.<anonymous> (/home/user/Projects/Javascript/Facebook/node_modules/puppeteer-core/lib/cjs/puppeteer/node/NodeWebSocketTransport.js:52:32)
    at callListener (/home/user/Projects/Javascript/Facebook/node_modules/ws/lib/event-target.js:290:14)
    at WebSocket.onMessage (/home/user/Projects/Javascript/Facebook/node_modules/ws/lib/event-target.js:209:9)
    at WebSocket.emit (node:events:514:28)
    at Receiver.receiverOnMessage (/home/user/Projects/Javascript/Facebook/node_modules/ws/lib/websocket.js:1192:20)
    at Receiver.emit (node:events:514:28)
    at Receiver.dataMessage (/home/user/Projects/Javascript/Facebook/node_modules/ws/lib/receiver.js:560:14) {
  cause: ProtocolError
      at <instance_members_initializer> (/home/user/Projects/Javascript/Facebook/node_modules/puppeteer-core/lib/cjs/puppeteer/common/CallbackRegistry.js:96:14)
      at new Callback (/home/user/Projects/Javascript/Facebook/node_modules/puppeteer-core/lib/cjs/puppeteer/common/CallbackRegistry.js:100:16)
      at CallbackRegistry.create (/home/user/Projects/Javascript/Facebook/node_modules/puppeteer-core/lib/cjs/puppeteer/common/CallbackRegistry.js:32:26)
      at Connection._rawSend (/home/user/Projects/Javascript/Facebook/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/Connection.js:91:26)
      at CdpCDPSession.send (/home/user/Projects/Javascript/Facebook/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/CDPSession.js:78:33)
      at next (/home/user/Projects/Javascript/Facebook/node_modules/puppeteer-extra-plugin-stealth/evasions/sourceurl/index.js:34:41)
      at CdpCDPSession.send (/home/user/Projects/Javascript/Facebook/node_modules/puppeteer-extra-plugin-stealth/evasions/sourceurl/index.js:75:16)
      at #evaluate (/home/user/Projects/Javascript/Facebook/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/ExecutionContext.js:211:50)
      at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
      at async ExecutionContext.evaluateHandle (/home/user/Projects/Javascript/Facebook/node_modules/puppeteer-core/lib/cjs/puppeteer/cdp/ExecutionContext.js:178:16)
}

Node.js v18.17.0

I want to be able to use the webAction function so if you have any idea of how I can fix the error you are more than welcome.

In the output it says that it entered Facebook correctly but this is not true, as as soon as the browser opened it closed immediately! And obviously it doesn t complete correctly the order statements (waitForSelector & utils.webType). Can someone explain me what is happening and how to be able to run this code without any error?

最佳回答

在你的网络行动职能中,你称这些职能,但你没有等待兑现这些承诺。

你们需要改变功用。 j 等待电话结果的档案:

module.exports = {
  webAction: async function (logger, msg, func, ...args)
  {
    return new Promise(async (resolve) => {
      let actionMessage, actionLevel;
      try
      {
        await func(...args);
        actionMessage = msg;
        actionLevel =  info ;
      }
      catch (error)
      {
        actionMessage = "Error while executing " + msg + " function.
---
" + error.message + "
---";
        actionLevel =  error ;
      }
      finally
      {
        logger.log({
          level: actionLevel,
          message: actionMessage
        })
      }
      console.log( Inside resolve Promise );
      resolve( Fullfilment value of Promise );
      console.log( Last line if resolve body );
    })
  },

  webType: async function (page, text, xpath)
  {
    await page.type(
      xpath, text,
      {delay: getRandomIntInRange(constants.minSpeed, constants.maxSpeed)}
    );
  },
};
问题回答

允诺的规则是,如果你关心命令或结果(你是,99%的时间),你需要<代码>await<>。 <代码>await是功能中的一种允诺,要把允诺链归还给电线人,才能等待。 目前,功能tawait func(。 <代码>webType,t等到page.type(

实际上,你的脚本在等待任何结果的情况下将数十份共同承诺付诸东流,因此,命令是任意的,错误与所有其他行动几乎得到保证。

https://stackoverflow.com/a/77843008/6243352” 根据你的法典,可以改进设计。 记录你的用户操作的一种做法是使用一种Proxy,并向每个电话发送page:

const puppeteer = require("puppeteer"); // ^21.6.0

const makeLogger = page => {
  return msg => {
    const handler = {
      get(target, propKey, receiver) {
        return (...args) => {
          return page[propKey](...args)
            .then(result => {
              // happy path logging here
              console.log(`${propKey}: ${msg}`);
              return result;
            })
            .catch(err => {
              // sad path logging here
              console.error(`${msg} (${err.message})`);
            });
        };
      }
    };
    return new Proxy({}, handler);
  };
};

// sample usage:
let browser;
(async () => {
  browser = await puppeteer.launch({headless: "new"});
  const [page] = await browser.pages();
  const p = makeLogger(page);
  await p("example.com").goto("https://www.example.com");
  const text = await p("get text content").$eval("h1", el => el.textContent);
  console.log("  got text:", text);
  await p("test throwing").evaluate("notExists.foobar");
  console.log("  done");
})()
  .catch(err => console.error(err))
  .finally(() => browser?.close());

产出:

goto: example.com
$eval: get text content
  got text: Example Domain
test throwing (notExists is not defined)
  done

你们应当能够在此融合我们的习俗记录,并适应信条。 如page,则采用封闭式办法,因此,您不必再多次按要求通过同样的参数。





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签