Leveraging Selenium for assessing the visibility of elements in Print media applications

Is there a way to use Selenium to determine if specific elements on a page will be visible when printed based on CSS @media rules?

While the isDisplayed method considers CSS, is there a way to specify a media type in Selenium?

Alternatively, are there other methods to ensure that desired elements appear on print versions of web pages while unwanted ones do not?

Note: JavaScript print buttons are not in consideration. Users will utilize standard browser print functions (Chrome, FF, and IE). @media css directives will dictate visible and hidden content. I seek to use Selenium as a testing tool to simulate a printer mode and check element visibility in the print preview.

Answer №1

I have successfully developed a script that accomplishes exactly what you requested: it conceals screen-only styles and converts print-only styles to be screen-only.

To implement this functionality, you will need to inject the following JavaScript using Selenium:

(function simulatePrint() {
    //Function to check if a style is specified for a particular media
    function hasMedia(list, media) {
        if (!list) return false;

        var i = list.length;
        while (i--) {
            if (list[i] === media) {
                return true;
            }
        }
        return false;
    }

    //Iterate through all the stylesheets
    for (var sheetNumber = 0; sheetNumber < document.styleSheets.length; sheetNumber++) {
        //Current stylesheet being processed
        var currentSheet = document.styleSheets[sheetNumber];

        //Output debug information
        console.info("Stylesheet #" + sheetNumber + ":");
        console.log(currentSheet);

        //First, verify if any media queries are defined on the <style> / <link> tag

        //Disable screen-only stylesheets
        if (hasMedia(currentSheet.media, "screen") && !hasMedia(currentSheet.media, "print")) {
            currentSheet.disabled = true;
        }

        //Show "print" stylesheets
        if (!hasMedia(currentSheet.media, "screen") && hasMedia(currentSheet.media, "print")) {
            //Add "screen" media query to display on screen
            currentSheet.media.appendMedium("screen");
        }

        // Obtain the CSS rules in a cross-browser compatible manner
        var cssRules;
        try {
            cssRules = currentSheet.cssRules;
        } catch (error) {
            console.log(error);
        }

        try {
          cssRules = currentSheet.rules;
        } catch (error) {
          console.log(error);
        }

        // Handle cases where currentSheet.rules is null
        if (!cssRules) {
            continue;
        }

        //Secondly, iterate through all the rules in a stylesheet
        for (var ruleIndex = 0; ruleIndex < cssRules.length; ruleIndex++) {
            //Current rule being inspected
            var currentRule = cssRules[ruleIndex];

            //Hide screen-only rules
            if (hasMedia(currentRule.media, "screen") && !hasMedia(currentRule.media, "print")) {
                //Since Rule.disabled doesn't work, we manipulate the media type to remove "screen" and add "print" so it remains hidden
                console.info('Rule.media:');
                console.log(currentRule.media)
                currentRule.media.appendMedium(':not(screen)');
                currentRule.media.deleteMedium('screen');
                console.info('Modified Rule.media:');
                console.log(currentRule.media)
            }

            //Display "print" rules
            if (!hasMedia(currentRule.media, "screen") && hasMedia(currentRule.media, "print")) {
                //Add "screen" media to show on screen
                currentRule.media.appendMedium("screen");
            }
        }
    }
})()

You can view a live demonstration of this script on JSFiddle.

Bookmarklet Feature

You also have the option to install it as a bookmarklet.

Additional Resources:

Please Note: This script has only been tested on Google Chrome and Mozilla Firefox. Compatibility with other browsers may vary.

Answer №2

Utilizing visual automation tools like Applitools can be beneficial in certain situations. Our team has integrated it into our testing process with positive results.

Answer №3


     // Using jQuery to print the window when a button is clicked
     
     function printWindow() {
         window.print();
     }
     
     // Adding a button in HTML to trigger the print function
     <button type="button" class="print-btn" value="Print Window" onclick="printWindow()"><i class="icon-print"></i> Print</button>
     
     // Customizing CSS for printing purposes
     @media print{
          .header{display:none;}
          .footer{display:none;}
          .leftside{display:none;}
          .rightside{display:block;}
     }

     // You can view an example of this code on JSFiddle: http://jsfiddle.net/example/12345/

Answer №4

Here's a smart solution I came up with:

  1. Is it safe to assume that the PRINT button will always be present on the html page, like in the jsfiddle.net example mentioned earlier?

  2. Can I limit the options for printing to just clicking on a print button within the html page, excluding FILE->PRINT or RIGHT CLICK->PRINT? Are there any other scenarios to consider?

  3. Lastly, can we assume that your selenium tests are designed to run exclusively in Chrome and not Firefox? This distinction is crucial since the PRINT function behaves differently between the two browsers. My solution is tailored specifically for Chrome.

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

Tips for achieving a gradual transformation of an element according to the scrolling position

I have been experimenting with using waypoints for two specific purposes. The first objective is to determine whether a user is scrolling up or down and if the container comes into view. However, this functionality is not working as expected. The sec ...

Unique take on the Material Design Lite Theme, customized with Gulp and Sass tweaks

I am interested in implementing a personalized version of a Material Design Lite "theme". MDL is essentially the CSS and JS components of Material Design that have been extracted for use in web applications. While MDL provides a web interface to generate ...

Tips for including vertical lines within text boxes to distinguish elements

I've been working on a simple form using CSS and HTML, but I'm struggling to add vertical lines to separate my text from the radio buttons. Right now, I'm just using '|' to divide them, but it's not the most visually appealing ...

Customized function enabling dynamic menu display based on varying screen dimensions

Looking for assistance with JS and jQuery as I am relatively new to it. Any help would be greatly appreciated... I'm currently working on a responsive header where I want to implement onclick functions for mobile and tablet resolutions only. I' ...

Having trouble centering elements correctly with Bootstrap 5

Just dipping my toes into the world of bootstrap and experimenting with some code. Encountered an issue when trying to center elements properly within columns: <div class="container"> <div class="row"> <div class= ...

Discovering a new element that has been dynamically added to a webpage after a drag and drop operation in selenium

https://i.sstatic.net/WGiwP.png Currently, I am developing a webpage with rappid js components. My goal is to enable dragging and dropping elements from the palette onto the grid, as shown in the screenshot. Each element dragged from the palette can be id ...

The fixed blocks are covering the Blueimp gallery within the relative container

Check out this DEMO I created to showcase something interesting. In this demo, you will find a basic example of setting up a blueimp gallery, a navigation bar, and a button. <div class="nav">nav</div> <div class="wrapper"> <div id ...

Can one leverage protractor to locate an element based on specific coordinates?

My SVG rectangle serves as a container for other SVG rectangles. I want to click on the container, but there may be an inner rectangle at the center of the container. If so, I want to click on the inner rectangle instead. Is it possible to use Protractor ...

Align a button to the left or right based on its position within the layout

On the left side, there is dynamic text and on the right side, a button is displayed as shown below: <div class="dynamic-text"> {{ dynamicText }} </div> <div class="some-button"> < ...

Creating a reference to a hyperlink or button in a variable

I am currently working on creating a login form for a school project website. The section that is posing a challenge for me is determining if I can assign a variable to a href or button. For instance, imagine that the href has the variable 'A' ...

Using a combination of a bootstrap class and a custom CSS class to enhance your website design

How do I apply two different classes? I have two HTML select fields where the user can choose either repair or another option in the first one. When the user selects one, the second field should appear. But it also needs to have a Bootstrap class: form-con ...

Overlaying div above vimeo player

I'm attempting to overlay a div on top of a Vimeo video, a task I anticipated would be straightforward but turns out to be more complex than expected. Below is the HTML code snippet: <div id="wrap"> <iframe id="video" s ...

What is the best way to achieve this effect with CSS?

Is there a way to create this design with CSS? I experimented with applying border CSS and rotating the DIV, but couldn't quite achieve the desired result. Here is an image for reference: https://i.stack.imgur.com/yW6wK.png ...

Verify whether a div element is styled in a specific manner

Upon initial load of my website, if the page is maximized or in fullscreen mode, the comBrand div will have specific CSS properties applied. However, during a resize event, I use the .css() function to adjust the properties of this element so it doesn&apos ...

What's the issue with the submit button not functioning on the form?

After downloading a sample form, I encountered the following code: <form id="login-user" method="post" accept-charset="utf-8" action="/home.html" class="simform"> <div class="sminputs"> <div class="input full"> <l ...

Using time.sleep() in Python with WebDriver to test an Angular 2 application

Query regarding the utilization of time.sleep() for testing an Angular2 application. I am aware of tools like Protractor (and Pytractor) which can be used for scripting functional tests in Selenium. Explicit Waits can also be employed. I came across this i ...

In Bootstrap 5, the content within flex box containers always aligns at the top, regardless of other factors

I've been struggling to vertically align flex items within a div using bootstrap 5. Despite trying various methods, I haven't had any success. I've even created a Stack Snippet that perfectly reproduces my issue. It seems like a simple CSS f ...

Issue with Running Selenium Chrome Driver in Docker Container

Looking for help with a new Docker project involving web scraping with Selenium and Python? Here's the setup: Dockerfile: FROM python:3.11-slim-buster # Install dependencies RUN apt-get update && apt-get install -y wget unzip # Download Chrom ...

Place a radio button on top of a div once the available space is depleted

Is there a way to make these radiobuttons hover over the topchoice and bottomchoice divs? I may need to adjust the width of choicefirstleft and choicesecondleft, potentially making it 100%. However, when the width approaches 100%, the radiobutton shifts do ...