Prevent the print dialog window from appearing when a page loads in Selenium for Firefox and Chrome

Is there a way to prevent the print window from automatically popping up when a page loads using Selenium?

So far, I have tried using the Robot class to press the escape key, but it only works 80% of the time. I have also experimented with Firefox preferences and overriding the window.print function.

Unfortunately, none of these methods completely disable the print window on page load. I am seeking guidance on how to achieve this specifically for Firefox and Selenium (Google Chrome solutions are optional).

I am unable to access the JavaScript code of the target website, as it is obfuscated, making it difficult to pinpoint which script triggers the print window on page load.


Upon further investigation, I discovered that the print window appears due to a specific piece of JavaScript code:

n.iframeNode.on('load', function () {
    n.iframeNode[0].elem.contentWindow.print()
}),

I have also attempted different approaches such as disabling JavaScript entirely, tinkering with JS events, and exploring proxy concepts without success.

If you have any insights or suggestions on how to effectively stop the print window from appearing on page load, please share them. Your assistance in resolving this issue would be greatly appreciated.

Answer №1

When dealing with the Chrome browser's print preview page, it is important to note that the controls are hidden within the ShadowDOM. In this case, it is recommended to interact with the "Cancel" button using Selenium rather than relying on Robot. This approach ensures better compatibility, especially when running tests in Selenium Grid or in parallel where managing focus between windows can be tricky.

To locate and click the "Cancel" button, you can follow this path:

https://i.sstatic.net/2TK85.png

You can then navigate to the button and trigger a click using the following Java code snippet:

new WebDriverWait(driver, 10).until(ExpectedConditions.numberOfWindowsToBe(2));
driver.switchTo().window(driver.getWindowHandles().stream().skip(1).findFirst().get());
WebElement printPreviewApp = driver.findElement(By.tagName("print-preview-app"));
WebElement printPreviewAppContent = expandShadowRoot(printPreviewApp, driver);
WebElement printPreviewSidebar = printPreviewAppContent.findElement(By.tagName("print-preview-sidebar"));
WebElement printPreviewSidebarContent = expandShadowRoot(printPreviewSidebar, driver);
WebElement printPreviewHeader = printPreviewSidebarContent.findElement(By.tagName("print-preview-header"));
WebElement printPreviewHeaderContent = expandShadowRoot(printPreviewHeader, driver);
printPreviewHeaderContent.findElements(By.tagName("paper-button")).get(1).click();

The expandShadowRoot function converts the given ShadowRoot into a Selenium WebElement, as shown below:

private WebElement expandShadowRoot(WebElement parent, WebDriver driver) {
    return (WebElement) ((JavascriptExecutor) driver).executeScript("return arguments[0].shadowRoot", parent);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating cookies in R Shiny: Storing variables for future use

Writing a fixed string to cookies can be done easily using methods like Cookies.set(\'cookie_2\', \'value\', { expires: 7 }) (see tutorial here). However, saving the variable user to cookie_2 may require a different ...

Guidance on implementing fallback font formats using FontFace API

I am exploring the FontFace API (not @fontface) and wondering if there is an easy way to include multiple font formats, similar to providing multiple sources in @fontface. Alternatively, is there a simple method to identify which font formats are supporte ...

Mixing strings with missing slashes in links

console.log(mylink) When using the console to log mylink, the expected result is a normal link like http://example.com/something.jpg. I tried concatenating it as shown below: var html = '<div id="head" style="background:linear-gradient(rgba(0, 0 ...

The JSON object, which has been converted into a string and sent over the network,

Attempting to set up a websocket server using TypeScript in Node.js, the following code was used: ws.on('message', (msg: string) => { console.log("got message:" + msg); const m = JSON.parse(msg); console.log(m); ...

What is the process of importing an IIFE-based JavaScript module into an Angular TypeScript application?

I have come across a third-party SDK that is structured as an oldschool IIFE based module. The code looks something like this: var ThirdPartySDK = (function() { var export = {}; // Adding some methods to export return export; })(); To use this SD ...

What steps should be followed to execute this moment.js code in an Angular.js controller using Node.js?

I am trying to adapt the following node.js code that uses moment.js into an AngularJS controller: var myDate = new Date("2008-01-01"); myDate.setMonth(myDate.getMonth() + 13); var answer = moment(myDate).format('YYYY-MM-DD'); To achieve this, I ...

How can I use Python to make Selenium click on a link that uses (ng-click)?

Looking for a way to click on a specific link with the 'toh' class using Python and Selenium in an HTML document with multiple links sharing similar classes and ids. <div Class="ibox-content"> <ul Class="sortable-list policy-list"&g ...

Spacing and filtering strings in a React array

i am attempting to include space to the names filtered by the filter, but all the names are coming back without any space. How can I modify the filtered array to have space between each name? here is how it currently looks like - https://i.sstatic.net/AznK ...

Tips for managing a basic click event within the Backbone.js framework

I am facing a challenge with a basic functionality in Backbone. I am trying to set up the <h1> element on my page so that when a user clicks on it, it smoothly navigates back to the homepage without a page reload. Here is the HTML snippet: <h1& ...

Webdriver will automatically open a file as soon as the download is complete

I am currently creating tests and utilizing the Firefox webdriver along with a FirefoxProfile to download a file from an external source. However, I need to be able to read this file immediately after it has finished downloading in order to extract specifi ...

Node.js: Breaking the Rules with an Illegal Break Statement

Struggling to generate a unique ID in Node.js and MongoDB, using a while loop that checks existing IDs in MongoDB until a unique value is found. If the ID is already taken, a number is added to the end until Mongo returns no results. Everything seems to b ...

delaying the alteration of an image attribute following an AJAX call

After clicking on a button, a function is triggered (think of it as a published/unpublished button). Immediately after the function is activated, I change the element to display a loader gif. function updateStatus(event, status, element, data, action) { ...

Is there a way to apply the active class without relying on an anchor element?

After creating a one-page website, I utilized JavaScript to prevent the hash from appearing in the URL. Here is the HTML code: <ul class="click crsl"> <li><a class="page1 dot active"></a></li> <li><a class=" ...

Implementing asynchronous loading of an image onto a webpage using JavaScript

Is it possible to asynchronously load an image specified in the src attribute of an HTML image tag? I am trying to invoke a Java class using an image src tag, but I want this to happen asynchronously without affecting the current functionality of the web ...

Could it be that this is a mysterious foreign alphabet or a problem with the encoding?

I'm facing a strange bug with characters on my website and I can't seem to figure out what's causing it. A foreign writer submitted an article to me, and when I received it, the font was displaying oddly. After some investigation, I've ...

jquery token selection dropdown box

I am not encountering any errors with this particular issue, however upon reviewing the plugin it appears that it should only toggle "admin admin" in the dropdown list. I am currently utilizing the most recent version of jquery. Upon further investigation ...

Utilizing EdgeDriver for Selenium with geolocation features and various extensions, all without the need for Selenium 4

I am working on a project for a large company that utilizes selenium 3 drivers for various browsers like Chrome, Firefox, and Edge. Recently, we started to integrate testing for Edge using Selenium and ran into an issue with additional arguments not being ...

Error in Next.js PDFtron Webviewer: ReferenceError - 'window' is not defined

Currently, I'm faced with a challenge in setting up a PDF viewer on my nextjs static page. Having recently ventured into Next.js, I'm seeking assistance from you guys to resolve this issue or suggest an alternative approach. While trying to imple ...

Having difficulty navigating to a link within a dynamic table cell using Selenium WebDriver and Java

In my current project, there is a dynamic table that I am working with. The task at hand involves locating a specific cell in the table and clicking on a link within it. While I have successfully navigated to the desired cell, I am facing difficulty in act ...

Which javascript libraries or game engines can be utilized to create a 3D environment with x, y, z coordinates to monitor the movement of objects?

Currently, I am working on developing a basic web application prototype that will showcase the real-time tracking of up to five individual objects within a predefined room. While I have explored the possibility of using three.js for this project, I am wond ...