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 */
};
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With