Retrieve the text from a JavaScript alert via Webdriver - c#

I'm creating a series of Webdriver tests which primary purpose are to ensure the validation of a web application page, so this revolves around ensuring the alert happens, but more importantly that the text displayed is correct and so the right validation is being triggered.
However I can't seem to get the text from the alerts.
I can't seem to find any info on retrieving the text from an alert and all research returns how to to simply accept the alert.
So far I have:
UnhandledAlertException alertText = UnhandledAlertException.GetAlertText();
Assert.That(alertText, Is.EqualTo("You must select the user's Primary Role"));
But "GetAlertText" isn't a thing recognized, I'm not sure if I need to get another file and reference it which contains this function or if it simply doesn't exist.
I was pretty sure there was a built in get alert text function but I appear to be wrong.
Thanks,
-Tom

Try to use this Alert class.
public String getAlert()
{
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
alert.accept();
return alertText;
}
Will return the text message of Alert from java script Alert function.
If a alert is with some kind of js framework which looks like error but its popup then use xpath to get the text of that locator.

If you are sure that the alerts are JavaScripts, then it is possible to get the alert text as below
string alertText = ((OpenQA.Selenium.IAlert)driverObj).Text;

Related

How can I set selected tab in EPiServer CMS edit view?

We have an EPiServer (forms) edit view with a number of tabs. The customer has requested that the tab which is #2 (called "alternative content"), should be automatically selected under certain conditions when the editors open the edit-page. We don't want to reorder the tabs. How can this be accomplished? We're running EPiServer 11.
Update:
I've tried to accomplish this using a Dojo-script. The result in EPiServer depends on how I set it up, which is kinda strange to me in this case. Here's the file
Web\modules\CMSDefaultTabSelector\module.config:
Here's how it's called in ModifyMetadata:
...and the script itself, CMSDefaultTabSelector.js, looks like this:
The result, depending on whether you send in EditLayoutContainer, Dialog, or skip it entirely (the way it should look), is as follows:
Result with EditLayoutContainer
Result with Dialog
The result as it should be
If I try to skip this parameter, I get the error "ctor is not a constructor". Other layout elements just render an empty tab, weirder errors, or you get other error messages. If I use require([...]), the function is called on every page reload, which is not what I want. I want it to only be called whenever the code from ModifyMetadata kicks in. Hope someone can help.
After fiddling around for quite a while, I finally found the magic code. Since other people might also wonder how this is done, here's how it was solved in the end (using Dojo):
define([
"dojo/_base/declare",
"epi/shell/layout/SimpleContainer"
],
function (
declare,
SimpleContainer
)
{
return declare([SimpleContainer], {
//constructor: function () {},
postCreate: function () { /* PostCreate fires too soon, and the tab strip is not completely rendered */ },
startup: function () {
// Use Jquery to select the tab we manually want to change to, and click it:
var tabElement = $("div.dijitContentPane span.tabLabel:contains('Additional content')");
if ($(tabElement).length) {
$(tabElement).trigger("click");
}
}
});
}
);

How to Update Textbox.Text on Button Press

Apologies for what is undoubtedly a newb question, but I have been unable to find a specific answer.
I have c#-integrated ASP.net Core project, with an SQL backend. I can run queries for individual entries just fine, but my problem is a far more mundane one.
I have a textbox, which I want to reload the page when the Enter key is pressed which the Text value appended to it. E.g. '~/GetPerson?name=' with the text the user's entered placed at the end.
This seems simple enough, and I'm probably missing the obvious, but I remain befuddled.
do you want this?
$("#textBox").on("keyup", function(e){
e.preventDefault();
if(e.keyCode===13){
//do call server or something
}
}
You can do something like this
$("#textBox").on("keyup", function(e){
e.preventDefault();
if(e.keyCode===13){
var name = (this).val();
window.location.href = '#Url.Action("GetPerson", "YourController")?name=' + name;
}
}

Click first email using selenium

I am trying to login to hotmail, and click the first email that is shown in the emails box.
I get a problem, when I'm trying to find the first email.
I've tried to get it in a lot of different ways, but I've wanted to make a test just by finding all the list items li, so I've made a simple function:
public void clickFirstEmail()
{
var lis = driver.FindElements(By.TagName("li")); //this is raising the exception
foreach (var li in lis)
{
MessageBox.Show(li.Text);
}
}
Whenever I try to access some elements, I get this exception: Permission denied to access property '__qosId'
I've seen some answers here on stackoverflow, but I guess they are right when you are running a selenium server.
I start my driver like this:
driver = new FirefoxDriver();
Any ideas on how to get this right ?
The whole plan is to click the first email.
UPDATE: I've tried one more time, and it worked, but it gave me this error now: Element is no longer attached to the DOM on the messagebox.show line.
I am thinking that the page (javascript) is constantly loading/changing new stuff, so what could I do about this ?

How to send alert to user via plugin without using InvalidPluginExecutionException?

I am currently using InvalidPluginExecutionException to send the message to the user, but it turns out that the message is in English "Business Process Error" beyond which the error box appears the button "download log file". This is not an error because the user is trying to duplicate a record, as can be seen in the code. Is there other way without having to use InvalidPluginExecutionException to show an alert?
QueryExpression query1 = new QueryExpression();
query1.ColumnSet = new ColumnSet(true);
query1.EntityName = "new_appraisers";
EntityCollection ec = service.RetrieveMultiple(query1);
if (ec.Entities.Count <= 0)
{
log.Tb_Log_Create("Appraiser created");
}
else
{
foreach (Entity app in ec.Entities)
{
if (app["fcg_appraiser"].ToString() == name)
{
log.Tb_Log_Create("appraiser allready exist");
throw new InvalidPluginExecutionException("The name allready exists");
}
if (app["new_login"].ToString() == login)
{
log.Tb_Log_Create("appraiser allready exist");
throw new InvalidPluginExecutionException("The login allready exists.");
}
}
}
The only method to display a message box to the user from a plugin is using an exception from the validation stage. You could use javascript however, perform a simple OData query on the On_Save event of the form, and display an alert box with whatever information you'd like, and cancel the saving of the form.
This would allow you to display whatever custom message you'd like, and keep the plugin from firing and displaying the download file dialog.
I may be little late, however, in more recent versions of CRM there are several possibilites to achieve what you want. The better ones beeing:
Business Rules
Validation using JS and notifying the user using
Form Notifications or
Control Notifications
I hope Microsoft doesn't read this but...
You can also use a synchronous Plugin and be happy with the Business Process Error Dialog popping off. I just found out that this Dialog is hackable to some degree. Just return HTML in the Exeptions Message like so:
throw new InvalidPluginExecutionException(
#"<img height='16px' src='http://emojione.com/wp-content/uploads/assets/emojis/1f644.svg'> <strong>Oh snap!</strong>
It seems the record can not be saved in its current state.
");
Which results in sth. like this:

How can you programmatically detect if javascript is enabled/disabled in a Windows Desktop Application? (WebBrowser Control)

I have an application which writes HTML to a WebBrowser control in a .NET winforms application.
I want to detect somehow programatically if the Internet Settings have Javascript (or Active Scripting rather) disabled.
I'm guessing you need to use something like WMI to query the IE Security Settings.
EDIT #1: It's important I know if javascript is enabled prior to displaying the HTML so solutions which modify the DOM to display a warning or that use tags are not applicable in my particular case. In my case, if javascript isn't available i'll display content in a native RichTextBox instead and I also want to report whether JS is enabled back to the server application so I can tell the admin who sends alerts that 5% or 75% of users have JS enabled or not.
Thanks to #Kickaha's suggestion. Here's a simple method which checks the registry to see if it's set. Probably some cases where this could throw an exception so be sure to handle them.
const string DWORD_FOR_ACTIVE_SCRIPTING = "1400";
const string VALUE_FOR_DISABLED = "3";
const string VALUE_FOR_ENABLED = "0";
public static bool IsJavascriptEnabled( )
{
bool retVal = true;
//get the registry key for Zone 3(Internet Zone)
Microsoft.Win32.RegistryKey key = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\3", true);
if (key != null)
{
Object value = key.GetValue(DWORD_FOR_ACTIVE_SCRIPTING, VALUE_FOR_ENABLED);
if( value.ToString().Equals(VALUE_FOR_DISABLED) )
{
retVal = false;
}
}
return retVal;
}
Note: in the interest of keep this code sample short (and because I only cared about the Internet Zone) - this method only checks the internet zone. You can modify the 3 at end of OpenSubKey line to change the zone.
If you are having troubles with popups popping up, i've included a solution for you, and if you want to disable/enable javascript on th client machine (or even just read/query if it is enabled/disabled) ive included that answer for you as well, here we go:
Which popup message do you want to disable? If it's the alert message, try this, obviously resolving the window or frame object to your particular needs, I’ve just assumed top-level document, but if you need an iframe you can access it using window.frames(0). for the first frame and so on... (re the JavaScript part)... here is some code, assuming WB is your webbrowser control...
WB.Document.parentWindow.execScript "window.alert = function () { };", "JScript"
You must run the above code only after the entire page is done loading, i understand this is very difficult to do (and a full-proof version hasn't been published yet) however I have been doing it (full proof) for some time now, and you can gather hints on how to do this accurately if you read some of my previous answers labelled "webbrowser" and "webbrowser-control", but getting back to the question at hand, if you want to cancel the .confirm JavaScript message, just replace window.alert with window.confirm (of course, qualifying your window. object with the correct object to reach the document hierarchy you are working with). You can also disable the .print method with the above technique and the new IE9 .prompt method as well.
If you want to disable JavaScript entirely, you can use the registry to do this, and you must make the registry change before the webbrowser control loads into memory, and every time you change it (on & off) you must reload the webbrowser control out and into memory (or just restart your application).
The registry key is \HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\ - the keyname is 1400 and the value to disable it is 3, and to enable it is 0.
Of course, because there are 5 zones under the Zones key, you need to either change it for the active zone or for all zones to be sure. However, you really don't need to do this if all you want to do is supress js dialog popup messages.
Let me know how you go, and if I can help further.
Here is a suggestion - Encode the warning into your webpage as default. Create a javascript that runs on page load which removes that element. The warning will be there when ever javascript is not allowed to run.
It's a long while since I coded client side HTML javascript to interact with the DOM so I may be a little out of date. i.e. you will need to fix details, but I hope I get the general idea across.
<script>
document.getElemntByID("noJavascriptWarning").innerHTML="";
</script>
and in your HTML body
<DIV id="noJavascriptWarning" name="noJavaScriptWarning">Please enable Javascript</DIV>

Categories

Resources