Is there a way for me to ensure that the value copied to my clipboard is accurate?

When I click a button in my process, it automatically copies an email address. How can I verify that the copied value matches my expectations? I was attempting to paste it into the terminal to check, but if there is a more efficient method to do this, I would appreciate any suggestions.

I attempted to import pyperclip based on another recommendation, but unfortunately, it did not import correctly.

Here is the code for the button that handles the copying functionality upon clicking:

@step('I locate the email icon and click')
def step_impl(context):
    window_before = driver.window_handles[0]
    context.current_element = context.wait.until(
        EC.element_to_be_clickable(
            (EMAIL_ICON)
        )
    )
    scroll_to_webelement(context.driver, context.current_element)
    time.sleep(3)
    context.current_element.click()

Upon clicking the button, it triggers the default email client to open a second window which we then close with the following step:

@step('I switch to the new window and close it')
def step_impl(context):
    context.wait.until(EC.number_of_windows_to_be(2))
    context.driver.switch_to.window(context.driver.window_handles[-1])
    context.driver.close()
    context.driver.switch_to.window(context.driver.window_handles[0])

My expectation is to retrieve the copied email, but so far none of my attempts have been successful.

Answer №1

Save your copied content into a variable and verify it through an assertion process. Give the following code a try and share your feedback.

Sample Python Script

import xerox
from selenium import webdriver

driver = webdriver.Chrome('/usr/local/bin/chromedriver')  
driver.implicitly_wait(15)

driver.get("https://clipboardjs.com/")
driver.find_element_by_xpath("//img[@alt='Copy to clipboard']").click() #copying content to clipboard
i = xerox.paste() #saving clipboard content to variable i
print i
print i == "npm install clipboard --save" #comparing clipboard content with expected value
driver.quit()

Expected Output:

npm install clipboard --save
True 

Answer №2

Here is an example of how you can conduct a test. Test HTML:

<!DOCTYPE html>
<html>
<body>
<input type="text" value="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="761b0f36131b171f1a5815191b">[email protected]</a>" id="mm">
<button onclick="myFunction()">Copy text</button>
<script>
    function myFunction() {
        var copyText = document.getElementById("mm");
        copyText.select();
        copyText.setSelectionRange(0, 99999)
        document.execCommand("copy");
        window.open();
    }
</script>
</body>
</html>

Test Code:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 5)
driver.get("file:///Users/***/Desktop/test.html")

# store input value
email = wait.until(ec.visibility_of_element_located((By.TAG_NAME, "input"))).get_attribute("value")
# click on button, that will copy value and open new tab
driver.find_element_by_tag_name("button").click()

# wait for the second window and switch to
wait.until(ec.number_of_windows_to_be(2))
driver.switch_to.window(driver.window_handles[-1])

# open google.com to check copied text
driver.get("https://www.google.com/")

google_q = driver.find_element_by_name("q")
# paste text to the google search input, SHIFT and INSERT keys for MacOS
google_q.send_keys(Keys.SHIFT, Keys.INSERT)
# assert copied value with stored
assert google_q.get_attribute("value") == email
# close current window and switch back to the first one
driver.close()
driver.switch_to.window(driver.window_handles[0])

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

Steps to launch Selenium or Puppeteer in a currently active authentic browser

Is there a way to open a new tab in my existing Chrome browser with all bookmarks and extensions, instead of opening a new browser just for testing? I would appreciate any short code snippet you can provide. Thank you! ...

Querying MongoDB using aggregation to find documents with a specific date range difference

I have been working on setting up a cron job to synchronize my documents. The goal is for the job to attempt syncing a specified number of times, but only after waiting at least 2 hours since the last attempt. Each document has a "lastSyncAt" field that I ...

React Hooks for Navigation in a Webpage (Auto-Resetting)

Trying to manage the display of different questions within a long form using Hooks has been a challenge. Utilizing useState for state management, the first two pages function correctly. However, upon clicking on the third page, it briefly flashes on the ...

What is the ideal way to utilize Vue within the framework of multiple pages?

When using the default Vue CLI setup, Vue is loaded from the index.html page. To work with Vue and dynamic content on the page, everything is typically handled in the App.vue file. But what if you want to make significant layout changes to the page? How d ...

Heroku experiences unexpected surge in memory consumption while using Puppeteer

Yesterday, a commit caused the process to hit Heroku's memory limit resulting in an R15 error. The code worked perfectly during testing and on Heroku until it reached a certain number of checked items, triggering the error. What's intriguing is t ...

Node.js MySQL User Verification

As a beginner in node JS, my current project involves authenticating users against a backend MYSQL database. Below is the code snippet responsible for handling authentication: function Authenticate(username, password, fn) { connection.connect(); ...

Browserify does not provide access to the require function in the browser environment

I am currently in the process of developing a web application using node.js along with express. My goal is to leverage Browserify in order to expose my local modules to the browser. Here is the structure of my application: ├── app.js ├── lib ...

Double Calling of Angular Subscription

I am currently working with a series of observables that operate in the following sequence: getStyles() --> getPrices() Whenever a config.id is present in the configs array, getStyles() retrieves a style Object for it. This style Object is then passed ...

Optimizing jqGrid: Enhancing saveRow function to properly synchronize with editRow function

Exploring how to customize jqGrid's add function for my own needs. I have a navButton with specific requirements: When the user clicks the button, a new row in edit mode should appear on the grid. Once the user enters data and presses enter, the dat ...

A ServiceWorker used a promise in FetchEvent.respondWith() that resulted in a non-Response value of 'undefined'. This caused an issue in browser-sync

There are times when my server encounters an error in the console: Failed to load ‘http://localhost:3000/browser-sync/socket.io/?EIO=3&transport=polling&t=Lm2wn4p’. A ServiceWorker passed a promise to FetchEvent.respondWith() that reso ...

Creating a list using variables through a Post Request in Express

I am currently exploring how to create a list using a Post Request in Express. I am fetching Video Game data from an API and aiming to use this data to populate specific details within a list. For illustration: let name = localStorage.getItem("name"); let ...

Selenium: The function moveToElement is not valid for the driver.actions() method

After creating all my tests using Selenium IDE, I decided to export them to JavaScript Mocha for running in travis. While the tests run smoothly in Selenium IDE and can be exported, I encountered an issue when trying to run them which resulted in the erro ...

Uncovering the Issue with Select All Functionality in <Table/> when using Material-UI and React

When using Material-UI's <Table/> with ReactJS, a table is set up with a select all checkbox. Each time an individual row checkbox is clicked, the row id is added to the state array clickedRowIds. This allows for logging of the ids of the clicke ...

Arranging DIVs in a vertical layout

Currently, I am working on a design that involves organizing several <DIV> elements in a vertical manner while still maintaining responsiveness. Here are some examples: Wider layout Taller layout I have tried using floats, inline-block display, ...

Unable to isolate segments of a string

Looking for a way to extract two different IDs from the following string: SPList:6E5F5E0D-0CA4-426C-A523-134BA33369D7?SPWeb:C5DD2ADA-E0C4-4971-961F-233789297FE9: using Javascript. The regular expression being used is : ^SPList\:(?:[0-9A-Za-z\-]+ ...

if there is an error in a JavaScript statement

<!DOCTYPE html> <html> <head> </head> <body> <hr> <div> <div id="myPosition"> </div> </div> <hr> <!--Storing the gun array --> <div id ...

Authenticate popup using Selenium (Java) without relying on waiting methods

What is the method for passing credentials in a pop up when requesting an HTTP application URL without using wait? Instead of utilizing wait, you can use the following code: driver.get(" URL"); ...

Determining the class or ID name of an element by assessing the value of a specific attribute

Is it possible to retrieve the class or ID names of all elements with a specific attribute value? For instance, given the code below: <rect class="rect0" x="45" y="0px" width="40px" height="40px" fill="#ff0000" selected="0"></rect> <rect cl ...

Angular component equipped with knowledge of event emitter output

I have a custom button component: @Component({ selector: "custom-submit-button" template: ` <button (click)="submitClick.emit()" [disabled]="isDisabled"> <ng-content></ng-content> </butto ...

When attempting to pass a token in the header using AngularJS, I encounter an issue with my NodeJS server

Error is: Possibly unhandled Error: Can't set headers after they are sent. at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11) at ServerResponse.res.set.res.header 1. All Node.js services were functioning properly before ...