Search code examples
javascriptphantomjsgoogle-chrome-devtoolsheadless-browser

Headless Chrome - trigger callback from loaded webpage


Is there a way to trigger a callback from the loaded webpage? I used to use PhantomJS where it was possible using following code:

 if (typeof window.callPhantom === 'function') {
    window.callPhantom({ data: 'RenderPDF' });
 }

And in the phantomjs script:

page.onCallback = function (data) {
   /* callback code */
};

Solution

  • You can evaluate javascript on the browser by using the evaluate function in the Runtime domain.

    Example below evaluates a function which returns a promise which will be resolved when window.callChrome is called.

    function callChrome() {
      return () => {
        return new Promise((resolve, reject) => {
          window.callChrome = resolve;
        });
      });
    }
    
    // runtime is located in the client object
    Runtime.evaluate({
      expression: `(${callChrome()})()`,
      awaitPromise: true,
    }).then((result) => {
      // what you've passed into the window.callChrome function.
    });
    

    The expression that is evaluated looks like this.

    (() => {
      return new Promise((resolve, reject) => {
        window.callChrome = resolve;
      });
    })()
    

    You should really run this piece of code once the page is ready. Ideally using the Page.loadEventFired function.