Is there any way how to force webdriver/internetexplorerdriver to open a site in compatibility mode. Every time I run my tests by Nunit all the history and compatibility mode list (where was my site listed before) are cleaned.
I can't change the code of the site. Can I add item to compatibility mode list or open site in specifi version of IE (I have 11 and I need open it in 7 with doc type 5).
Unfortunately no, unless you change the source code. As a workaround I use VMS. If you want to use the same route consider using free VMs from Microsoft. See my another answer related to question here
This is better description of my issue: I need to test a site that I can't edit. The site works only in compatibility mode in my IE 11 (it is made for ie 7 doc type 5). I want to run tests and cookies should be cleaned before that. But if I set "EnsureCleanSession = true" it cleans compatibilty list in IE besides cookies. Because of it, it's not possible to test the site.
I have found possible solution, but I have to test it... I've found out that compatibility list is in registry and I can load its value before it is cleaned and set the value again:
const string keyName = #"HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\BrowserEmulation\ClearableListData";
var a = Registry.GetValue(keyName, "UserFilter" , "Return this default if NoSuchName does not exist.");
// value of registry is removed
Registry.SetValue(keyName, "UserFilter", a);
Console.ReadLine();
But as I said, I don't know if it will do the trick...
[UPDATE]
Ok, it works with small work-around (because IE must be restarted after change in registry)
[SetUp]
public void SetUp()
{
//read the compatibility mode list from registry
const string path = #"HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\BrowserEmulation\ClearableListData";
const string key = "UserFilter";
var regValue = Registry.GetValue(path, key, "Return this default if NoSuchName does not exist.");
//run IE driver with cleaning of cookies and history
var options = new InternetExplorerOptions
{
IntroduceInstabilityByIgnoringProtectedModeSettings = true,
EnsureCleanSession = true
};
_driver = new InternetExplorerDriver(IeDriversPath, options);
//cloase IE
_driver.Quit();
_driver.Dispose();
//put the compatibility mode list back into registry
Registry.SetValue(path, key, regValue);
//run IE driver without cleaning of cookies and history
options.EnsureCleanSession = false;
_driver = new InternetExplorerDriver(IeDriversPath, options);
}
Related
Sorry didn't find a similar question and maybe somebody can help.
Due to additional requirements we have to test our project not only with Chrome but with Firefox as well. When we simply changed a test context to Firefox it turned out that all calls of findElement took 10 times more time than with Chrome. All tests are completely ruined. We tried to use different test machines but the results are the same. The project is on Core .Net. For testing we use MSTest V2, Firefox 63 (64 bit) and Geckodriver 0.22 (64 bit) .
Very appreciate any help.
By referring to the previous answer, my issue was solved by below code.
string geckoDriverDirectory = "Path of geckodriver.exe"
FirefoxDriverService geckoService =
FirefoxDriverService.CreateDefaultService(geckoDriverDirectory);
geckoService.Host = "::1";
var firefoxOptions = new FirefoxOptions();
firefoxOptions.AcceptInsecureCertificates = true;
Driver = new FirefoxDriver(geckoService, firefoxOptions);
Yep. You’re definitely hitting the performance issue that is part of .NET Core. It doesn’t happen on Chrome, IE, or Edge, because the driver executables for each of those browsers (unlike geckodriver) listen on both the IPv4 and IPv6 loopback addresses. If you were to specify “::1” as the host for geckodriver with .NET, the problem would disappear.
Refer to https://github.com/SeleniumHQ/selenium/issues/6597
A complete .Net Core webdriver for Firefox 7/14/2020:
// .Net Core workaround #1: Slow Firefox webdriver
string projectFolder = Directory.GetParent(Directory.GetCurrentDirectory()).FullName;
string geckoDriverDirectory = projectFolder + "\\netcoreapp3.1\\";
FirefoxDriverService geckoService =
FirefoxDriverService.CreateDefaultService(geckoDriverDirectory);
geckoService.Host = "::1";
var ffOptions = new FirefoxOptions();
ffOptions.BrowserExecutableLocation = #"C:\Program Files\Mozilla Firefox\Firefox.exe";
ffOptions.AcceptInsecureCertificates = true;
// This profile will by-pass *ALL* credentials. Note that Chrome uses Internet Explorer settings, so it does not need this.
// You must pre-setup the profile, by launching Firefox and doing phone authentication
// The profile's location is: C:\Users\<windows logon>\AppData\Local\Mozilla\Firefox\Profiles
// Without this, if your AUT uses SSO, you will always get prompted for the PIN or Two factor authentication
FirefoxProfile profile = new FirefoxProfileManager().GetProfile("Selenium");
ffOptions.Profile = profile;
// DotNet Core workaround #2- Code page
// https://stackoverflow.com/questions/56802715/firefoxwebdriver-no-data-is-available-for-encoding-437
// https://stackoverflow.com/questions/50858209/system-notsupportedexception-no-data-is-available-for-encoding-1252
CodePagesEncodingProvider.Instance.GetEncoding(437);
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
_driver = new FirefoxDriver(geckoService, ffOptions);
In case anyone is trying gary.zhang's answer in Javascript, it looks like this:
let driver = new Builder()
.forBrowser('firefox')
.setFirefoxService(new firefox.ServiceBuilder('path_to_driver', host='::1'))
.setFirefoxOptions(new firefox.Options().headless())
.build();
Took me a bit of staring at it to figure out how to convert the syntax.
I am attempting to control two browser windows via selenium using c# and a single chromedriver. The reason being that I need to share session details accross browser windows.
The code that I have tried and failed with is below;
var options = new ChromeOptions();
options.AddArguments("chrome.switches", "--disable-extensions --disable-extensions-file-access-check --disable-extensions-http-throttling --disable-infobars --enable-automation ");
options.AddUserProfilePreference("credentials_enable_service", false);
options.AddUserProfilePreference("profile.password_manager_enabled", false);
options.PageLoadStrategy = PageLoadStrategy.Default;
ChromeDriverService service = ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true;
var Driver = new ChromeDriver(service, options);
//THIS WILL OPEN A NEW WINDOW. BUT BECAUSE IT IS A NEW DRIVER DOES NOT WORK FOR SHARING SESSION DETAILS.
//var TestDriver = new ChromeDriver(service, options);
//TestDriver.Manage().Window.Maximize();
//THIS JUST OPENS UP A NEW TAB. NOT A NEW WINDOW (IT WOULD SEEM MOST DOCUMENTATION SUGGESTS THAT IT SHOULD)
IJavaScriptExecutor jscript = Driver as IJavaScriptExecutor;
jscript.ExecuteScript("window.open();", "google.com.au");
//TRY USING THE SEND KEYS TECHNIQUE. NOTHING HAPPENS
var test = Driver.FindElement(By.TagName("html"));
test.SendKeys(Keys.Control + "n");
test.SendKeys(Keys.Control + "t");
//TRY AGAIN USING THE SEND KEYS TECHNIQUE USING A DIFFERENT TAG. NOTHING HAPPENS
var blah = Driver.FindElements(By.TagName("body"));
blah[0].SendKeys(Keys.Control + "t");
//TRY USING ACTIONS. NOTHING HAPPENS
Actions action = new Actions(Driver);
action.SendKeys(OpenQA.Selenium.Keys.Control + "n");
action.Build().Perform();
I may resort to AutoIt to open a browser if I have to, but one more dependency is not what I need. Documentation everywhere around the web seems to suggest than all the options I tried above should work...I suspect it may be a chromedriver issue of some kind.
Any ideas on how to achieve my goal would be greatly appreciated
UPDATE.
Arnons answer below lead me to the solution. If you are in a similar situation the best thing to do is just open up the browser console (from developers tools) and experiment with javascript until you get what you want. Then just execute that. In the end executing the following code has worked for me.
IJavaScriptExecutor jscript = Driver as IJavaScriptExecutor;
jscript.ExecuteScript("window.open('https://www.bing.com.au','_blank','toolbar = 0, location = 0, menubar = 0')");
The other alternative was to use Autoit, which I also got working, much easier than I did figuring out the javascript. But one less dependency is best :)
UPDATE2.
Further complications arise with trying to control the window as an independent browser window. I believe any new window created from a parent window, has the same process id (at least my testing has indicated so), and for all intense and purpose is treated as a tab in the selinium driver. I therefore conclude that certain things are just not possible (for example relocating the child browser window on the screen).
Your first attempt using ExecuteJavaScript was very close, but In order for it to open a new window instead of new tab, you should add the following arguments: `"_blank", "toolbar=0,location=0,menubar=0" to it.
See this question for more details.
I should have read the question better, here is my solution. Ended up using this for selecting windows that popped up after clicking a button but should work with swapping between windows.
//---- Setup Handles ----
//Create a Handle to come back to window 1
string currentHandle = driver.CurrentWindowHandle;
//Creates a target handle for window 2
string popupWindowHandle = wait.Until<string>((d) =>
{
string foundHandle = null;
// Subtract out the list of known handles. In the case of a single
// popup, the newHandles list will only have one value.
List<string> newHandles = driver.WindowHandles.Except(originalHandles).ToList();
if (newHandles.Count > 0)
{
foundHandle = newHandles[0];
}
return foundHandle;
});
//Now you can use these next 2 lines to continuously swap
//Swaps to window 2
driver.SwitchTo().Window(popupWindowHandle);
// Do stuff here in second window
//Swap back to window 1
driver.SwitchTo().Window(currentHandle);
// Do stuff here in first window
You need to explicitly tell Selenium which tab you wish to interact with, which in this case would be;
driver.SwitchTo().Window(driver.WindowHandles.Last());
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.
I am trying to use the Selenium Internet Explorer driver but it is breaking when I try to instantiate it:
[TestInitialize]
public void TestInitialise() {
ieDriver = new InternetExplorerDriver();
}
with the following error:
Enable Protected Mode must be set to the same value (enabled or
disabled) for all zones. (NoSuchDriver).
I have found an apparent solution to my problem here, which suggests setting the driver's DesiredCapabilities, as shown:
var capabilitiesInternet = new OpenQA.Selenium.Remote.DesiredCapabilities();
capabilitiesInternet.SetCapability("ignoreProtectedModeSettings", true);
IWebDriver webDriver = new InternetExplorerDriver(capabilitiesInternet);
The only problem is, I am using the latest version of the driver that I could find, and there is no override for InternetExplorerDriver that takes DesiredCapabilities as a parameter.
Is there some new or other way of setting DesiredCapabilites now instead of the example that I used?
That setting will work around the problem but introduce some subtle problems. Have you not set up the Protected Modes of IE correctly? This is the correct solution to it.
Guide of this lives here:
https://github.com/SeleniumHQ/selenium/wiki/InternetExplorerDriver
Essentially just turn off protected mode in IE for each zone.
Alternatively if you really must use the override capability, then you either do two things:
Use the InternetExplorerOptions class. Note the name of the property, it gives you a big clue it is not a good idea to use it.
var options = new InternetExplorerOptions;
options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
var driver = new InternetEplorerDriver(options);
or use the RemoteWebDriver, which can take in any implementation of the ICapabilities interface, which DesiredCapabilites implements:
var capabilities = new DesiredCapabilities("internet explorer", string.Empty, new Platform(PlatformType.Windows));
capabilities.SetCapability("ignoreProtectedModeSettings", true);
var webDriver = new RemoteWebDriver(capabilities);
This blog post by Jim Evans (a Selenium contributor) gives a really in depth view of the context surrounding this exception. I will quote it here for posterity:
In IE, from the Tools menu (or the gear icon in the toolbar in later versions), select "Internet options." Go to the Security tab. At the bottom of the dialog for each zone, you should see a check box labeled "Enable Protected Mode." Set the value of the check box to the same value, either checked or unchecked, for each zone. Here's the dialog for reference:
Note that you don't have to change the slider for security level, and you don't have to disable Protected Mode. I routinely run with Protected Mode turned on for all zones, as I think it provides a more secure browsing experience.
Note: This only worked for me when turning protected mode off.
I couldn't modify the protected mode settings manually on my system since they were disabled. But the below VBA snippet for updating the registry values did the trick for me.
Const HKEY_CURRENT_USER = &H80000001
strComputer = "."
Set ScriptMe=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
strComputer & "\root\default:StdRegProv")
'Disable protected mode for local intranet'
strKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\1\"
strValueName = "2500"
dwValue = 0
ScriptMe.SetDWORDValue HKEY_CURRENT_USER,strKeyPath,strValueName,dwValue
'Disable protected mode for trusted pages'
strKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\2\"
strValueName = "2500"
dwValue = 0
ScriptMe.SetDWORDValue HKEY_CURRENT_USER,strKeyPath,strValueName,dwValue
'Disable protected mode for internet'
strKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3\"
strValueName = "2500"
dwValue = 0
ScriptMe.SetDWORDValue HKEY_CURRENT_USER,strKeyPath,strValueName,dwValue
'Disable protected mode for restricted sites'
strKeyPath = "Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\4\"
strValueName = "2500"
dwValue = 0
ScriptMe.SetDWORDValue HKEY_CURRENT_USER,strKeyPath,strValueName,dwValue
msgbox "Protected Mode Settings are updated"
Just copy paste the above code into notepad and save it with .vbs extension and double click it!
Now try running your automation script again
This Question and Answer may also be of use to anyone trying to deal with Protected Mode issues. I couldn't get it to work via the Internet Explorer Options pane and ended up having to adjust the registry manually.
Im developing a custom browser solution with .net's Webbrowser control.
To disable the IE-Compatibilty View, I set the registry entry
Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION:
[Sreenshot regedit] http://zbirk.mirk.at/browserreg.png "Screenshot"
i tried to use the values: dword=8000,dword=8888,dword=9000, but the webbrowser control seems to ignore these reg entries.
Maybe someone had this problems too and may help me.
The WebBrowser control definately DOES respect these keys.
Remember that while taskman may show application.exe in the name column, if you are debugging the exe name is application.vshost.exe
So in my application sI just attempt to create the key every time the app runs. If it fails to create it (because it already exists) then I continue running, if it creates the key then I inform the user that they need to restart the application.
ensure that you are not running within vshost
the app name would be different ie appname.vshost.exe
Thx for your reply, now its working.
Her is my working peace of code:
public void setIEcomp()
{
String appname = Process.GetCurrentProcess().ProcessName+".exe";
RegistryKey RK8 = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Internet Explorer\\Main\\FeatureControl\\FEATURE_BROWSER_EMULATION",RegistryKeyPermissionCheck.ReadWriteSubTree);
int value9 = 9999;
int value8 = 8888;
Version ver = webBrowser1.Version;
int value = value9;
try
{
string[] parts = ver.ToString().Split('.');
int vn = 0;
int.TryParse(parts[0], out vn);
if (vn != 0)
{
if (vn == 9)
value = value9;
else
value = value8;
}
}
catch
{
value = value9;
}
//Setting the key in LocalMachine
if (RK8 != null)
{
try
{
RK8.SetValue(appname, value, RegistryValueKind.DWord);
RK8.Close();
}
catch(Exception ex)
{
//MessageBox.Show(ex.Message);
}
}
}
I too could not see that FEATURE_BROWSER_EMULATION made any difference in my application.
I was testing the FEATURE_BROWSER_EMULATION functionality by manually editing the registry with regedit. Nothing I did made any difference. My hosted page was still failing on any new-ish JavaScript and could not load external libraries.
I found my mistake:
I was editing the 64-bit view of the registry with regedit. My app was running as a 32-bit app and looking at the 32-bit view of the registry. That's why my changes to the registry seemed to have no impact on my application. By the way, the WPF project template defaults to "Prefer 32-bit."
Manually editing with regedit within the Wow6432Node key worked:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION
Of course, setting the DWORD value programmatically within your application will also work, since your 32-bit application will edit within the Wow6432Node.
An older post and solution is no longer accurate.
Running procmon and watching for FEATURE_BROWSER_EMULATION shows the following registry variables actually checked. This was for WINWORD.exe but other than that - take your pick...
HKU\S-1-5-21-[my-sid-paws-off]\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION\WINWORD.EXE
HKU\S-1-5-21-[my-sid-paws-off]\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION*
HKLM\SOFTWARE\Microsoft\Office\ClickToRun\REGISTRY\MACHINE\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION(Default)
HKLM\SOFTWARE\Microsoft\Office\ClickToRun\REGISTRY\MACHINE\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION\WINWORD.EXE
HKLM\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION\WINWORD.EXE
HKLM\SOFTWARE\Microsoft\Office\ClickToRun\REGISTRY\MACHINE\Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION*
HKLM\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION*