Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 */
};
like image 733
JensVanhooydonck Avatar asked Jun 04 '17 11:06

JensVanhooydonck


People also ask

How do I run Chrome in headless mode?

As we have already seen, you just have to add the flag –headless when you launch the browser to be in headless mode. With CLI (Command Line Interface), just write: chrome \<br> – headless \ # Runs Chrome in headless mode. <br> – disable-gpu \ # Temporarily needed if running on Windows.

How do I use Chrome headless in selenium?

ChromeOptions options = new ChromeOptions() options. addArgument("headless"); ChromeDriver driver = new ChromeDriver(options); In the above code, the browser is instructed to run in the headless mode using the addArgument() method of the ChromeOptions class provided by the Selenium WebDriver.

Is Chrome 60 is a headless Web browser?

Starting with version 60, the Chrome browser introduced the ability to run in headless mode. We now have the ability to launch the browser without creating a visual browser window.

How do I run Chrome headless in Linux?

You can run Google Chrome in headless mode simply by setting the headless property of the chromeOptions object to True. Or, you can use the add_argument() method of the chromeOptions object to add the –headless command-line argument to run Google Chrome in headless mode using the Selenium Chrome web driver.


1 Answers

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.

like image 155
David Hooper Avatar answered Oct 21 '22 03:10

David Hooper