How to launch a Google Chrome Tab with specific URL using C# - c#

Is there a way I can launch a tab (not a new Window) in Google Chrome with a specific URL loaded into it from a custom app? My application is coded in C# (.NET 4 Full).
I'm performing some actions via SOAP from C# and once successfully completed, I want the user to be presented with the end results via the browser.
This whole setup is for our internal network and not for public consumption - hence, I can afford to target a specific browser only. I am targetting Chrome only, for various reasons.

As a simplification to chrfin's response, since Chrome should be on the run path if installed, you could just call:
Process.Start("chrome.exe", "http://www.YourUrl.com");
This seem to work as expected for me, opening a new tab if Chrome is already open.

// open in default browser
Process.Start("http://www.stackoverflow.net");
// open in Internet Explorer
Process.Start("iexplore", #"http://www.stackoverflow.net/");
// open in Firefox
Process.Start("firefox", #"http://www.stackoverflow.net/");
// open in Google Chrome
Process.Start("chrome", #"http://www.stackoverflow.net/");
For .Net core 3.0 I had to use
Process process = new Process();
process.StartInfo.UseShellExecute = true;
process.StartInfo.FileName = "chrome";
process.StartInfo.Arguments = #"http://www.stackoverflow.net/";
process.Start();

UPDATE: Please see Dylan's or d.c's anwer for a little easier (and more stable) solution, which does not rely on Chrome beeing installed in LocalAppData!
Even if I agree with Daniel Hilgarth to open a new tab in chrome you just need to execute chrome.exe with your URL as the argument:
Process.Start(#"%AppData%\..\Local\Google\Chrome\Application\chrome.exe",
"http:\\www.YourUrl.com");

If the user doesn't have Chrome, it will throw an exception like this:
//chrome.exe http://xxx.xxx.xxx --incognito
//chrome.exe http://xxx.xxx.xxx -incognito
//chrome.exe --incognito http://xxx.xxx.xxx
//chrome.exe -incognito http://xxx.xxx.xxx
private static void Chrome(string link)
{
string url = "";
if (!string.IsNullOrEmpty(link)) //if empty just run the browser
{
if (link.Contains('.')) //check if it's an url or a google search
{
url = link;
}
else
{
url = "https://www.google.com/search?q=" + link.Replace(" ", "+");
}
}
try
{
Process.Start("chrome.exe", url + " --incognito");
}
catch (System.ComponentModel.Win32Exception e)
{
MessageBox.Show("Unable to find Google Chrome...",
"chrome.exe not found!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}

Related

Open a default browser window using c# and Process.Start

I am trying to open a web page using the default browser when someone hits an API endpoint.
I have this working on my local test machine:
[HttpGet("Http/{classId}")]
public void OpenWebLink(Guid classId)
{
string target = "http://astrolab.meeting.trl.edu/class/details.aspx?classId=" + classId;
System.Diagnostics.Process.Start("C:\\Program Files\\Mozilla Firefox\\firefox.exe", target);
}
But when I publish to a server that has IIS, it can't find firefox.exe
The problem is, I had to put the full path to firefox just to get it to work on my machine. If I didn't include the path like that I'd get this error:
System.Diagnostics.Process.Start Win32Exception: 'The system cannot find the file specified.'
I also tried this:
[HttpGet("Http")]
public void OpenWebLink(Guid classId)
{
try
{
var ps = new ProcessStartInfo("http://astrolab.meeting.trl.edu/class/details.aspx?classId=" + classId;)
{
Verb = "open"
};
Process.Start(ps);
}
catch (Win32Exception w32Ex)
{
throw w32Ex;
}
}
But it still fails when I hit the endpoint on the IIS server with this:
System.ComponentModel.Win32Exception (2): The system cannot find the file specified.
Is there a way to set it up so that it will find the default browser on any machine?
Thanks!
It's as if dotnet developers are unaware of other operating systems besides Windows...
#Blindy's answer only works on Windows, but nowhere did they indicate this. And even if #SkyeBoniwell's question mentions IIS which implies Windows, neither the title of the question, nor the body, nor the tags explicitly mention Windows. As such, keeping in mind stackoverflow answers are meant to be used by everyone and not only the OP of a question, a correct answer to this thread should theoretically be os-agnostic. In practice, it should take into account as many operating systems as possible, i.e. at the very least the main three ones.
Here is a solution that works for 99% of end-user systems:
public static void OpenBrowser(string url)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Process.Start("xdg-open", url);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Process.Start("open", url);
}
else
{
// throw
}
}
taken from here
Either use ShellExecute to launch your url (the more correct way), or pipe it through explorer (the lazier, less portable way).
Process.Start(new()
{
UseShellExecute = true,
FileName = "http://google.ca",
});
Process.Start("explorer.exe", "http://google.ca");

Microsoft Edge not stay open when run by Microsoft WebDriver

My OS Build: 16299.309 so
I download MS WebDriver, ver. 5.16299 release: 16299, from https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
My SetEdgeDriver() method in C#:
private IWebDriver SetEdgeDriver()
{
try
{
var path = #"C:\FolderWhereMSWebDriverExeFile ";
var option = new EdgeOptions();
option.PageLoadStrategy = PageLoadStrategy.Normal;
return new EdgeDriver(path, option);
}
catch (Exception)
{
throw;
}
}
When the unit test is executed, Edge browser opens briefly then it closes with an error saying "Unexpected error. Unknown error"
The test is just about going to Google search site and works fine with Chrome.
I have followed this: Edge browser crashing after initial watir-webdriver launch
but no luck. Please advice.
You can try a different constructor:
IWebDriver wrappedWebDriver = new EdgeDriver(new EdgeOptions());
This works for me. No need to specify the folder. Also, think that the normal search patter is the default one.

how to get already opened IE browser handle in selenium?

I have one already opened IE browser , with some url.
After this, I Run below code which will open another IE browser. however it gives me only one window handle in below code.
Is it possible to get previously opened IE browser handle ?
IWebDriver IEdriver = new InternetExplorerDriver();
IReadOnlyCollection<String> browsers = IEdriver.WindowHandles;
foreach (String item in browsers)
{
IEdriver.SwitchTo().Window(item);
String url = IEdriver.Url;
}
I think this is what you're looking for:
String winHandleBefore = driver.getWindowHandle();
//Do whatever operations you have to do
for(String winHandle : IEdriver.getWindowHandles()){
IEdriver.switchTo().window(winHandle);
}
Be careful as what you are trying to do, is not robust solution to write tests cases. If one test case causes browser to crash you will be getting all the test cases failed.
Also I don't think it should be possible to get handles on previously opened window by default, because when you write code
IWebDriver IEdriver = new InternetExplorerDriver();
It calls for a constructor of InternetExplorerDriver class and opens new instance of Internet Explorer.
You can either go for close all browsers before starting your test case execution by killing the ie process from task manager.
foreach (Process process in Process.GetProcessesByName("iexplore"))
{
process.Kill();
}

Re-using a specific iexpore window by updating its URL

I have an application that monitors a file, and based on its contents launches a browser using this code:
Process.Start("iexplore", "-nomerge " + fullUrl);
Now as with many small projects, the requirements have changed. The change is that only one browser can be launched from my program at a time.
Also, another program is capable of launching a browser with another url, and I cannot shut it down, eliminating the option of just closing down all instances of iexplore and then launching mine. ( which is what I did originally )
Is there a way to launch a browser and continue to keep control of it so you can update the URL of that specific instance of iexplore using c#?
This code is close to what is in the answer on the duplicate post, but is slightly different, so I am sharing it here.
foreach (SHDocVw.InternetExplorer ie in new SHDocVw.ShellWindowsClass())
{
if (ie.FullName.ToLower().Contains("iexplore") &
ie.LocationURL.ToLower().Contains("&qtype=mine"))
{
ie.Visible = true;
ie.Navigate(fullUrl);
openNewBrowserWindowWindow = false;
}
}
if (openNewBrowserWindowWindow) {
SHDocVw.InternetExplorerClass IE = new SHDocVw.InternetExplorerClass();
IE.Visible = true;
IE.Navigate(fullUrl);
}

Selenium IEDriver- Regarding PATH variable

I am working on creating a regression test suite using Selenium for IE Browser. I am using the IEDriver exe from Selenium website. As per instructions from Selenium,
"The Internet Explorer Driver Server
This is required if you want to make use of the latest and greatest features of the WebDriver InternetExplorerDriver. Please make sure that this is available on your $PATH (or %PATH% on Windows) in order for the IE Driver to work as expected."
Approach 1
I tried to setup PATH variable via batch file as follows
setlocal
set varC=%CD%\ChromeDriver
set varI=%CD%\IEDriver
set PATH=%PATH%;%varC%;%varI%
However i still face issues with IEDriver not working properly.
Approach 2
When i set PATH variable via "Advanced System Settings", everything seems to be working fine. Can someone confirm if this setting can't be done via batch file or if i am performing some wrong operation?
Here is how I am initializing driver
[OneTimeSetUp]
public void SetupTestFixture()
{
switch (ConfigPara.TestBrowser.ToLower())
{
case "ie":
Utility.KillProcess("iexplore");
DesiredCapabilities caps = DesiredCapabilities.InternetExplorer();
caps.SetCapability("ignoreZoomSetting", true);
caps.SetCapability("nativeEvents", false);
caps.SetCapability("allow-blocked-content", true);
caps.SetCapability("disable-popup-blocking", true);
caps.SetCapability("allowBlockedContent", true);
aOptIE = new OpenQA.Selenium.IE.InternetExplorerOptions();
aOptIE.InitialBrowserUrl = ConfigurationManager.AppSettings.Get("baseURL");
aOptIE.EnablePersistentHover = false;
aOptIE.RequireWindowFocus = true;
aOptIE.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
System.Environment.SetEnvironmentVariable("webdriver.ie.driver", ConfigPara.IEDriverDirectory.FullName +"\\IEDriverServer.exe");
Utility.Instance.driver = new InternetExplorerDriver(ConfigPara.IEDriverDirectory.FullName, aOptIE);
break;
}
Utility.Instance.driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(7));
baseURL = ConfigPara.BaseURL;
Utility.Instance.wait = new OpenQA.Selenium.Support.UI.WebDriverWait(Utility.Instance.driver, TimeSpan.FromSeconds(30));
//utility = new Utility(driver);
}
[OneTimeTearDown]
public void SetupTestTeardown()
{
try
{
Utility.Instance.driver.Quit();
Utility.Instance.driver.Dispose();
}
catch (Exception)
{
// Ignore errors if unable to close the browser
}
Assert.AreEqual("", verificationErrors.ToString());
}
Hi actually you have to set the path of the IE driver that you downloaded form here http://docs.seleniumhq.org/download/
please do it like below
System.setProperty("webdriver.ie.driver","pathofIEdriver\\IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver();
User below code for C# webdriver:
System.Environment.SetEnvironmentVariable("webdriver.ie.driver", "Path\IEDriverServer.exe");
You can use webdriver manager class to handle it.
WebDriverManager.iedriver().setup();
Added in your maven pom file :
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>3.8.1</version>
</dependency>
You can also use Webdrivermanage dependency for Gradle. This will automatically maintain IE driver exe file.

Categories

Resources