您如何使用打字稿将从本地文件导出的函数注入到puppeteer中?

我有两个文件,都是打字稿:puppeteer.tsasync-some.ts

async-some.ts导入另一个文件,该文件包含some函数的异步版本。

// async-some.ts
import { someP } from "../helpers/arrays"

window.someP = someP

export default someP

异步some的源文件:

// helpers/arrays.ts
export const someP = <T>(arrayP: T[],fn: (item: T) => Promise<boolean>) =>
  new Promise(async (resolve,reject) => {
    for (const item of arrayP) {
      if (await fn(item)) {
        resolve(true)
        break
      }
    }
    resolve(false)
  })

最后,是使用page.addScriptTag函数的木偶文件:

{
  // ...

  // this is supposed to allow external javascript to be imported into
  // the pages puppeteer traverses.
  await page.setBypassCSP(true)

  // this works - it adds isEmpty to the window object,which can be
  // used like: await window.isEmpty(...). However,it only excepts
  // strings. If I try to pass a function,which is the way the async
  // some is designed to work,the function will come in as null.
  await page.exposeFunction("isEmpty",isEmpty)

  // I saw that the `addScriptTag` should be wrapped in a "framenavigated" 
  // event listener in a suggestion on a git issue.
  page.on(
    "framenavigated",async frame =>
      frame === page.mainFrame() &&
      (await page.addScriptTag({
        // content: someP.toString(),// content: `${someP}`,// path: path.resolve(__dirname,"../injections/async-some.ts"),path: "./async-some.ts",// type: "module",})),)

  // I don't think this alone works.
  // await page.addScriptTag({ path: "./async-some.ts" }))
}

page.addScriptTag中的注释中可以看出,我尝试了很多事情,在google中搜索了力所能及的解决方案,翻阅了每篇甚至包含{{1}的单词}和puppeteer

使用addScriptTag添加脚本时,出现以下错误:

path: "./async-some.ts"

当我将A parser-blocking,cross site (i.e. different eTLD+1) script,is invoked via document.write. The network request for this script MAY be blocked by the browser in this or a future page load due to poor network connectivity. If blocked in this page load,it will be confirmed in a subsequent console message. See URL for more details.文件放在另一个目录中时,稍后会导致404错误,因此我将puppeteer初始化到了该目录中。在代码中,尝试使用{{1} }函数将产生async-some.tsasyncSome。那里没有运气。另外,我不确定asyncSome(...) is not a function对此如何发挥作用。人偶文档是我见过的最糟糕的文档之一,以至于毫无用处。

使用await window.asyncSome(...) is not a functiontype: "module"都以相同的方式失败。

请告诉我我在做错什么。

lz407854504 回答:您如何使用打字稿将从本地文件导出的函数注入到puppeteer中?

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/2947314.html

大家都在问