我有两个文件,都是打字稿:puppeteer.ts
和async-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.ts
或asyncSome
。那里没有运气。另外,我不确定asyncSome(...) is not a function
对此如何发挥作用。人偶文档是我见过的最糟糕的文档之一,以至于毫无用处。
使用await window.asyncSome(...) is not a function
和type: "module"
都以相同的方式失败。
请告诉我我在做错什么。