Harshit Gupta
Harshit Gupta

Reputation: 23

Handle Print Preview window using selenium in chrome latest version

I'm trying to work with a Print Dialog box in google chrome version 75.0.3770.80. I am clicking on cancel button on print dialog using Selenium to close it.

Print Dialog box

The cancel button can be inspected and its selectors are visible on the UI but when I am trying to click on those selectors using selenium it is given No such element exception.

Inspecting Cancel button

Also, when I am using getSource() for that page button selectors are not present in the source code but are visible on UI

So, how can we click on cancel button is there any way to do this?.

Upvotes: 1

Views: 7153

Answers (2)

o-az
o-az

Reputation: 625

So many way, way too complicated answers. Here's a better one:

What you need to be doing doing here is basically grabbing the default JavaScript function that triggers the print pop-up/dialog and assigning it to an empty function:

window.print = "function(){};"

Above is how you would do it in Python. Try to translate this to Java.

Upvotes: 0

supputuri
supputuri

Reputation: 14135

Here is the solution in python. You can convert this method to java.

def cancelPrintPreview():
    # get the current time and add 180 seconds to wait for the print preview cancel button
    endTime = time.time() + 180
    # switch to print preview window
    driver.switch_to.window(driver.window_handles[-1])
    while True:
        try:
            # get the cancel button
            cancelButton = driver.execute_script(
                "return document.querySelector('print-preview-app').shadowRoot.querySelector('#sidebar').shadowRoot.querySelector('print-preview-header#header').shadowRoot.querySelector('paper-button.cancel-button')")
            if cancelButton:
                # click on cancel
                cancelButton.click()
                # switch back to main window
                driver.switch_to.window(driver.window_handles[0])
                return True
        except:
            pass
        time.sleep(1)
        if time.time() > endTime:
            driver.switch_to.window(driver.window_handles[0])
            break

You can check my answer here for more information on working with shadow-root elements.

Upvotes: 1

Related Questions