Puppeteer - 删除由exposeFunction 公开的函数?

sar*_*isa 6 javascript webautomation node.js puppeteer

我以下列方式使用exposeFunction-command:

await this.page.exposeFunction('foo', function(){ return 'bar'; });
Run Code Online (Sandbox Code Playgroud)

这按预期工作,并为我提供了 window.foo 函数。

如果我再次调用此代码,则会出现以下错误:

Error: Failed to add page binding with name foo: window['foo'] already exists!
Run Code Online (Sandbox Code Playgroud)

使用 page.goto() 导航时,此错误甚至仍然存在。

有没有办法解除exposeFunction()公开的函数的绑定?

har*_*ded 5

您可以更改存储在地图中的功能_pageBindings。这非常棘手,因为您会更改内部变量,但这是解决此问题的唯一方法。

await this.page.exposeFunction('foo', function(){ return 'bar'; }); 
this.page._pageBindings.set('foo', function(){ return 'baz'; });
Run Code Online (Sandbox Code Playgroud)

  • @vexingCoder,风险在于这不是 API 的一部分。因此,木偶操作者可以根据需要重命名“_pageBindings”,从而破坏您的代码。 (2认同)