Suppose you copy a link by clicking on the button and you want to open that copied link in a new tab, then how to perform this operation in selenium C#.
driver.FindElement(By.Id("button")).click(); -----from this operation we just copy the link.
Question: Now How to open this copy link in new tab ?
CodePudding user response:
After getting the URL link with code like this:
var url = driver.FindElement(By.Id("button")).Text;
You can open a new tab and switch to it with
((IJavaScriptExecutor)driver).ExecuteScript("window.open();");
driver.SwitchTo().Window(driver.WindowHandles.Last());
And then open the previously saved url there with driver with
driver.Url = url;
So that the entire code could be something like this:
var url = driver.FindElement(By.Id("button")).Text;
((IJavaScriptExecutor)driver).ExecuteScript("window.open();");
driver.SwitchTo().Window(driver.WindowHandles.Last());
driver.Url = url;
In case you are getting the URL by clicking on that element as you mentioned driver.FindElement(By.Id("button")).click();
so that the URL is copied into the clipboard, you can use code like this:
using System.Windows.Forms;
driver.FindElement(By.Id("button")).click();
string url = Clipboard.GetText()
((IJavaScriptExecutor)_chromeDriver).ExecuteScript("window.open('" url "');");
CodePudding user response:
Copied link will be present in the clipboard, and once you've opened a new tab using this:
driver.SwitchTo().NewWindow(WindowType.Tab);
You could just do this:
driver.Navigate().GoToUrl(Clipboard.GetText());
if you are facing
The name 'Clipboard' does not exist in the current context
after that line of code, you would have to import:
using System.Windows.Forms;
This also could result in below fault:
The type or namespace name 'Forms' does not exist in the namespace 'System.Windows' (are you missing an assembly reference?
for that you'll have to go inside your project directory and then go to the project file and add
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<UseWPF>true</UseWPF>
<UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>
this should solve the issue.
#Approach 2:
((IJavaScriptExecutor)driver).ExecuteScript("navigator.clipboard.readText().then(text => window.location.replace(text));");