Selenium C# InPrivate Mode Internet Explorer IE 11 throws exception - selenium

I have a requirement to open IE11 in private-mode on Winodws10. Tried by following code but it is throwing exception "Unexpected error launching Internet Explorer. Unable to use CreateProcess() API. To use CreateProcess() with Internet Explorer 8 or higher, the value of registry setting in HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth must be '0'."
Code:
int val = Convert.ToInt32(Microsoft.Win32.Registry.GetValue("HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\TabProcGrowth", "", -1));
InternetExplorerOptions ops = new InternetExplorerOptions();
ops.ForceCreateProcessApi = true;
ops.BrowserCommandLineArguments = "-private";
IWebDriver driver = new InternetExplorerDriver(url, ops);
There is key in RegEdit and i can read successfully.

Removing ops.ForceCreateProcessApi = true; helps to start the browser, but NOT in private mode. You need the combination of
ops.ForceCreateProcessApi = true;
ops.BrowserCommandLineArguments = "-private";

I had a problem just like yours. I searched a lot and found no solution until I tried to delete the following line:
ops.ForceCreateProcessApi = true;
And thank God, the problem was solved. I'd love to know if it helped you solve the problem

Related

How to disable SmartScreen (safebrowsing in edge) on C# Selenium Edge Chromium?

I'm trying to run some selenium C# end-to-end tests on Edge Chromium browser. One of the tests does a download check, basically it downloads a xml file and check whether it exists in the downloaded location.
I'm using Microsoft.Edge.SeleniumTools EdgeOptions to construct options for the EdgeDriver.
But the issue right now is that Edge blocks downloads.
Tried different sorts of things but none of them worked.
Same issue can be solved on Chrome by disabling "safebrowsing" on UserProfilePreferences in ChromeOptions.
I know for a fact that SmartScreen does the blocking, if that is so is there any profile preference that I can use to disable SmartScreen ?
Or any other workaround to force download without the block would be very helpful.
For testing purposes, I suggest you create HashMap objects and try to set Edge preferences like below.
static void Main(string[] args)
{
HashMap<String, Object> edgePrefs = new HashMap<String, Object>();
edgePrefs.put("profile.default_content_settings.popups", 0);
edgePrefs.put("profile.default_content_setting_values.notifications", 2);
edgePrefs.put("profile.default_content_setting_values.automatic_downloads" , 1);
edgePrefs.put("profile.content_settings.pattern_pairs.*,*.multiple-automatic-downloads",1);
var options = new EdgeOptions();
egdeOptions.setExperimentalOption("prefs",edgePrefs);
options.UseChromium = true;
options.BinaryLocation = #"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe"; // Here add the Edge browser exe path.
var driver = new EdgeDriver(#"Edge_driver_path_here...", options); // Here modify the selenium web driver path.
driver.Navigate().GoToUrl("http://website_URL_here...");
driver.FindElementById("lnk1").Click();
}
If the issue persists then I suggest you set the default download directory like below.
options.AddUserProfilePreference("download.default_directory", #"D://Folder1");
See whether it help to download the file.
I was trying to find the answer with the usage of W3C WebDriver Protocol, but it seems like the only possible way is to turn off XML Edge SmartScreen policies using Windows Registry:
public void SetEdgeXmlDownloadPolicy()
{
var keyName = #"HKEY_CURRENT_USER\Software\Policies\Microsoft\Edge\ExemptDomainFileTypePairsFromFileTypeDownloadWarnings";
var valueName = "AllowXmlDownload";
var valueData = #"{""domains"": ["" * ""], ""file_extension"": ""xml""}";
var currentValue = Registry.GetValue(keyName, valueName, string.Empty).ToString();
if (currentValue == string.Empty || !currentValue.Contains("xml"))
Registry.SetValue(keyName, valueName, valueData, RegistryValueKind.String);
}
Credits to this workaround goes to IndianCodeMaster

Unable to find browser object in RFT 8.5

I installed RFT 8.5 and JRE 7. When I run the scripts it's not finding browser object.
Below is the code which I have used in RFt to find the brwoser object.
Dim Allobjects() as TestObeject
Allobjects=RootTestObject.GetRootTestObject.Find(".class","Html.HtmlBrowser"))
Here it's is returning Allbects.lenth=0. Because of the I am getting struck.
Anybody can help me how to resolve this issue.
Note: I am using IE8
I was not able to find the browsers using RootTestObject either. But it is possible to find the browser windows using the Html domains:
startApp("Google");
startApp("asdf");
sleep(5);
DomainTestObject[] dtos = getDomains();
List<DomainTestObject> htmlDomains = new ArrayList<DomainTestObject>();
for (DomainTestObject dto : dtos) {
if (dto.getName().equals("Html")) {
htmlDomains.add(dto);
}
}
List<BrowserTestObject> browsers = new ArrayList<BrowserTestObject>();
for (DomainTestObject htmlDomain : htmlDomains) {
TestObject[] tos = htmlDomain.getTopObjects();
for (TestObject to : tos) {
if (to.getProperty(".class").equals("Html.HtmlBrowser")) {
browsers.add((BrowserTestObject) to);
}
}
}
System.out.println("Found " + browsers.size() + " browsers:");
for (BrowserTestObject browser : browsers) {
System.out.println(browser.getProperty(".documentName"));
}
Output:
Found 2 browsers:
https://www.google.ch/
http://www.asdf.com/
First, I start 2 browsers. Then I get all Html domain test objects. After that, I get all top objects and check whether their class is Html.HtmlBrowser.
I hope there is a simpler solution—looking forward to seeing one :)
Try the below code Snippet:
Dim Allobjects() As TestObject
Allobjects = Find(AtDescendant(".class", "Html.HtmlBrowser"))
Hope it helps.
Browser is a toplevel window so what you can do is :
Dim Allobjects() as TestObeject
Allobjects=Find(AtChild(".class","Html.HtmlBrowser"))
'The above code expects the browser to be statically enabled , also RootTestObject is not needed as implicitly RFT will use the RootTestObject if no anchor is provided.
Also if the browser is not statically enabled then you could also use:
DynamicEnabler.HookBrowsers() API so that browsers get enabled.

selenium proxy configuration multiple times in same browser

I opened a browser(any) with selenium tool and applying proxy to that browser by this below posted code, below is for Firefox
//LINE 1 FirefoxProfile profile = new FirefoxProfile();
//LINE 2 profile.setPreference("network.proxy.http", configuration
.getProxyConfiguration().getHostname());
//LINE 3 profile.setPreference("network.proxy.http_port", configuration
.getProxyConfiguration().getPort());
//LINE 4 profile.setPreference("network.proxy.type", configuration
.getProxyConfiguration().getType().toInt());
//LINE 5 return new FirefoxDriver(profile);
Now, I want to apply another proxy configuration for the same browser(Because, If I use another browser, session will be get change, So.... I want to apply my changes to that browser itself). How to apply my proxy configuration to the same browser. When I use same code I've to return driver which uses "NEW". I showed in my code(//LINE 5). Please help me to solve this issue.
Thanks:
Ramakrishna K.C
You can create Proxy with Kind = ProxyKind.System
new Proxy { Kind = ProxyKind.System};
Then update the internet settings in the registry
var proxyServer = string.Format("http={0};https={0}", ipAddressAndPort);
var proxyEnable = enableProxy ? 1 : 0;
const string subKeyPath = #"Software\Microsoft\Windows\CurrentVersion\Internet Settings";
using (var subKey = Registry.CurrentUser.CreateSubKey(subKeyPath))
{
if (subKey == null)
{
throw new Exception(string.Format("Failed to create or open subKey. SubKeyPath: {0} ", subKeyPath));
}
subKey.SetValue("ProxyServer", proxyServer, RegistryValueKind.String);
subKey.SetValue("ProxyEnable", proxyEnable, RegistryValueKind.DWord);
}
otherwise use PAC file in firefox profile.
http://findproxyforurl.com/

Google Spellcheck

I'm unable to access the Google spell check service located at this address:
https://www.google.com/tbproxy/spell
is anyone else having this problem? I keep getting "bad gateway" when I try to connect. I'm pretty sure the service is offline.
Is there any news on what's going on? I know Google Drive went down a few weeks ago with the same set of error messages.
You can try this below Java code. This doesn't require any API Key. But please note, if you run it frequently, it will stop working as google blocks the IP Address from making future calls. You can use it on small data set. Not ideal solution, but if it is part of some batch job which runs in a while, then this approach may be acceptable to you.
public static String getSpellCheckedText(String Text) throws Exception {
String google = "http://www.google.com/complete/search?output=toolbar&q=";
String search = Text;
String charset = "UTF-8";
String spellCheckedText = Text;
URL url = new URL(google + URLEncoder.encode(search, charset));
Reader reader = new InputStreamReader(url.openStream(), charset);
BufferedReader bufReader = new BufferedReader(reader);
String line = bufReader.readLine();
StringBuffer sBuffer = new StringBuffer();
while (line != null) {
sBuffer.append(line).append("\n");
line = bufReader.readLine();
}
String content = sBuffer.toString();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(content));
Document document = builder.parse(is);
NodeList nodeList = document.getElementsByTagName("suggestion");
if (nodeList != null && nodeList.getLength() > 0) {
org.w3c.dom.Node elm = nodeList.item(0);
if (elm.getNodeType() == Node.ELEMENT_NODE) {
Element suggestionElement = (Element)elm;
String suggestedString = suggestionElement.getAttribute("data");
if (suggestedString != null && suggestedString.trim().length() != 0) {
spellCheckedText = suggestedString.trim();
System.out.println(Text + " => "+ spellCheckedText);
}
}
}
return spellCheckedText;
}
I am also having this problem. I am getting a 503 Server Error. The problem is definitely on Google's end. (N.B. I am on Safari 6.0.3)
In specific...
503. That's an error.
The service you requested is not available at this time.
Service error -27. That’s all we know.
It seems as though Google is having some problems with their services. Hopefully they fix it soon!
Ditto, here. I really depend on it to check spelling in text boxes. It says "Unable to connect to Google spelling servers. Please check your internet connection and try again"

Start Default Browser - Windows

When starting the default browser like this:
Dim trgt1 As String = "http://www.vbforums.com/showthread.php?t=612471"
pi.FileName = trgt1
System.Diagnostics.Process.Start(pi)
It takes about 40 seconds to open the page.
If I do it like this, though this isn't the default browser
Dim trgt1 As String = "http://www.vbforums.com/showthread.php?t=612471"
pi.Arguments = trgt1
pi.FileName = "iexplore.exe" 'or firefox.exe
System.Diagnostics.Process.Start(pi)
it opens immediately. Is this a bug or a feature? I have tried this with both IE and FireFox set to be the default browser.
1
Windows is running through the registry looking for an appropriate application to open the document with (via explorer.exe).
2
You are explicitly telling windows to use xxx.exe to open the document.
Update for the moving target: ;-)
The reason it is so slow is that the Url you are specifying doesn't look like anything it knows how to open, with a browser or otherwise, and has to employ brute force in determining this.
If you wan to speed up launching with the default browser, get it from HKEY_CURRENT_USER\Software\Classes\http\shell\open\command and use #2.
Use this function to retrieve path of default browser
/// <summary>
/// Reads path of default browser from registry
/// </summary>
/// <returns></returns>
private static string GetDefaultBrowserPath()
{
string key = #"htmlfile\shell\open\command";
RegistryKey registryKey =
Registry.ClassesRoot.OpenSubKey(key, false);
// get default browser path
return ((string) registryKey.GetValue(null, null)).Split('"')[1];
}
Opens URL in default browser from within the C# program.
string defaultBrowserPath = GetDefaultBrowserPath();
try
{
// launch default browser
Process.Start(defaultBrowserPath, "http://www.yahoo.com");
}
catch (Exception exp)
{
MessageBox.Show(exp.Message);
}
Opens URL in separate instance of default browser from within the C# program.
// open URL in separate instance of default browser
Process p = new Process();
p.StartInfo.FileName = GetDefaultBrowserPath();
p.StartInfo.Arguments = "http://www.yahoo.com";
p.Start();
From this blog post
I respectfully differ with the Sky. I have tried this on numerous machines now and the value
string key = #"htmlfile\shell\open\command";
seems to always default to IE even if Chrome is set to the default browser. Now, to be honest I have not tried this on machines with firefox set to the default browser only chrome, so it could do with more testing but the value does seem to only store IE from my testing.
Hope this helps those who use alternative browsers.
I am going to stick with process.start(url) as that pretty much guarantees that you get the users default browser every time. Let the framework handle it! that is why MS built it...