Search code examples
javascriptnode.jspuppeteerwebautomation

Puppeteer - Remove function exposed by exposeFunction?


I am using the exposeFunction-command in the following manner:

await this.page.exposeFunction('foo', function(){ return 'bar'; });

This works as intended and gives me the window.foo-function.

If I call this code again, I get the following error:

Error: Failed to add page binding with name foo: window['foo'] already exists!

This error even persists when navigating with page.goto().

Is there a way to unbind a function exposed by exposeFunction()?


Solution

  • You could change the function stored in the `_pageBindings` map. This is quite hacky because you would change an internal variable, but it's the only way to solve this.
    await this.page.exposeFunction('foo', function(){ return 'bar'; }); 
    this.page._pageBindings.set('foo', function(){ return 'baz'; });
    

    UPDATE April-2024
    Puppeteer 20.6 introduced removeExposedFunction. You can do this:

    await this.page.exposeFunction('foo', function(){ return 'bar'; }); 
    await this.page.removeExposedFunction('foo');