How to handle alert pop up with JavaScript? Selenium Webdriver - javascript

Selenium WebDriver 2.53.1.1
Visual Studio 2015
C#
The application I am testing has Alert Pop Ups which I handle with the following bit of code without problem
ts.getDriver().SwitchTo().Alert().Accept();
However I have ran into a new issue. Some of my webelements have issues of not being found anymore and therefore I have to run JavaScript to execute the web element (please see code below for handling the web element)
public void SelectHREFCID()
{
IJavaScriptExecutor js = ts.getDriver() as IJavaScriptExecutor;
js.ExecuteScript("arguments[0].click()",hrefCID);
try
{
ts.getDriver().SwitchTo().Alert().Accept();
}
catch (NoAlertPresentException)
{
// do nothing...
}// Have to use this to find the hyperlink!
}
The only problem is immediately after js.ExecuteScript line runs, the Pop Up Displays and my Alert().Accept() line of code never fires off after this so the program just stops there with the pop up. I ran this line by line in debug and can't can't step to the next line once I execute the js.ExecuteScript line. Any advice on how to handle this?
UPdate At this point in my code (js.ExecuteScript))
, as soon as this line of code is executed i see this
Once this pop up displays My Selenium Code does not continue into the try catch statement to handle the Alert
Latest update as of 9/9
I tried the alert handle both ways
But my selenium code stops execution at the point of the pop up firing off
js.ExecuteScript("arguments[0].click().hrefCID);
**UPDATE 09/12****
I updated my window.alert and this resolved the issue (to confirm)
IJavaScriptExecutor js = ts.getDriver() as IJavaScriptExecutor;
js.ExecuteScript("window.confirm = function(){return true;}");
js.ExecuteScript("arguments[0].click()",hrefCID);
// js.ExecuteScript("window.alert = function() { return true;}");

I think this alert blocks the code execution, you should execute this script before click to override the confirmBox function using js as :-
js.ExecuteScript("window.confirm = function() { return true;}")
After that execute as below to perform click on button :-
js.ExecuteScript("arguments[0].click()",hrefCID);

Related

Javascript errors effect on browsers

I provide some additional services to websites that add my script to their site. Technically my script does not interact with actual functionality of the site, the most is does is read some information and the main part of the code only runs only after the event (think something like Google Analytics).
Recently a bug caused an "X is undefined" error to occur in some circumstances and the client insists that this error is crashing their site. They sent me a screenshot that shows a blank page and a console screenshot that shows the error but they removed my code so I was not able to see it in real time.
My question is if there is any possibility that these types of errors can affect the website. For example assume this code runs on the website:
var tmp = Sizzle('h1');
tmp[0].innerHTML = "test";
Assume that for some reason Sizzle is not defined when the code runs or that there weren't any H1 elements on the page so tmp is empty. Could the resulting error under any circumstances affect the outside environment. e.g the page the code runs on? Obviously if I had overwritten the body element then yes it will affect the website but my question is only about "x is undefined" or syntax errors.
An Error will break the execution of the current function-stack.
For example if you have a onclick event, that calls a function and you have an error at the beginning it will not execute anything after that code. But that doesn't mean that any JavaScript on your Website won't work anymore. Everything will still be fine and run. Of cause if there was something important that was not executed after an Error it would change the logic of your runtime.
You can also avoid Error to go down the function-stack with a try-catch block:
function a() {
var x = new DoesNotExist()
alert("test a") // this will not alert() as there is an error before
}
function b() {
try {
var x = new DoesNotExist()
} catch (e) {}
alert("test b") // this will alert because the error is catched
}
alert("code is running")
a()
b() // this will not execute as a() broke this script
// however pressing the button b will still alert in b() as it's in a new stack
alert("code finished")
<input onclick="a()" value="a" type="button" />
<input onclick="b()" value="b" type="button" />
Yes, there are circumstances that error of the type "X is undefined" affects the whole website.
If the code which produces "X is undefined" error is:
inside a function or inside an object method - it will stop this current function from execution but likely will proceed with the script below it.
written as a row by row Javascript statements it will stop on this current point and won't proceed with else script.
Probably your client has more Javascript statements (loading content of the page) below the crashing pont, these statements are not executed and the content is not loaded.
You can simply add to your script:
if (typeof variable !== 'undefined')
{
// else part of the code
}
As JavaScript is a scripting language which alters the DOM and provides user interaction I'd say: in general as long as you do not interfere with the site's content it will not affect the page being loaded. There are two possibilities I could imagine stopping the page from showing up:
your javascript lead to a infinite loop and therefore blocks the content being loaded (but they should have gotten an error like the page not reacting)
the depend the building of their page on stuff they intended to do using your code so it will not load because it doesn't have your code

Cancel button was tapped when nothing is done

I did read those three posts:
Handling Alert with UIAutomation
UIAutomation : Cancel button on Alert view is tapped without actually doing it
UIATarget.onAlert = function onAlert(alert) Issue - Script doesn't seem to go into block correctly
and I know this issue can be fixed. I tried to use the methods which people came up with in the posts but it doesnt really work for me. I would like to ask here again...
So I need to type a password on the alert window. Like this:
target.frontMostApp().keyboard().typeString("1234");
I was wondering if I should write the onAlert function first, and put this line of code after the onAlert function? Or write the onAlert function first, and then put this line of code inside the onAlert function?
I tried to do something like this:
UIATarget.onAlert = function onAlert(alert)
{
return true;
target.frontMostApp().keyboard().typeString("1234");
}
But it is not working... The cancel button is still being tapped... Thanks!
I see two problems. First, the typeString line will never be executed because it comes after the return line in the function.
function myExampleFunc() {
{
doSomething(); // executes
return true; // exits from the function
doAnything(); // never executed. ever.
}
The second thing is that it looks like you're trying to catch an alert that's generated by your own application:
target.frontMostApp().keyboard().typeString("1234");
You don't use onAlert to catch these; onAlert is for handling iOS alerts like permissions popups.

How does the the line after the javascript popupwindow works?

OK I have a method from the code behind that creates a popupwindow. Then there's a line of code that executes after that Im wondering when does that line of code executes, If it executes after using the popupwindow or right after it creates the popupwindow?
EX:
void exPopupWindowMethod()
{
string scr = "window.open('examplePopup.aspx','popup_window',.....);";
ClientScript.RegisterStartupScript(this.GetType(), "script", scr, true);
}
String example = "example"; //initialization
exPopupWindowMethod();// the method that creates the popup window
example=null;
I dont know if theres a duplicate question for this but pls consider my question. I need to clarify this for using of sessions thanks!
The example=null line will be executed immediately (i.e. before the popup window is shown).
The reason for this is that the ClientScript.RegisterStartupScript wraps the code in a document.ready loop which will wait until the rest of the page has completed loading before executing.
Because the example=null line isn't waiting for the rest of the DOM to load, it will execute immediately.
ClientScript.RegisterStartupScript on MSDN
Just replace the code after the popup with something like : Response.Write("Test");
And check if the response is done while or after the popup shows?

How to debug dynamic JavaScript functions in FireBug

I have some JavaScript functions like this:
function onSelectRow_${itemid}(){
something;
}
This it is appearing like this in Firebug script tab:
function onSelectRow_87878(){
something;
}
I put multiple break points (it has more than 20 lines, I put one in for example) in Firebug -> Script tab.
But the problem is, Firebug is not able to do debug these methods, ie. it is not stopping execution it executing as usual. I tried multiple times.
This is my actual code and use:
function onSelectRow_${escapedId }(rowId){
}
<jqgrid:grid onSelectRow="onSelectDeviceRow_${escapedId }"
What can I try to resolve it?
You can use debugger
function onSelectRow_87878()
{
debugger; //add here
something;
}
When you open Firebug, enable Script,and it will automatically go to the debugger point
debugging in firefox

IE9 not running javascript onload

For some reason, IE9 is not running my JavaScript code onload when the browser is launched for the first time that session. It seems to only run onload after the user refreshes the page. It will also run the JavaScript when the debug console is open.
How do I make it so the JavaScript runs onload after the browser is open? Is this just a bug of IE9?
I'll restate this so you understand: The code DOESN'T run if you go to the site after launching a new browser session. The code DOES run if you open the site in a new tab, or reload the page, or open the debug console
Here is the function I use to run my script onload (which works fine in NORMAL browsers):
(function (i) {
var u = navigator.userAgent;
var e = /*#cc_on!#*/
false;
var st = setTimeout;
if (/webkit/i.test(u)) {
st(function () {
var dr = document.readyState;
if (dr == "loaded" || dr == "complete") {
i()
} else {
st(arguments.callee, 10);
}
}, 10);
} else if ((/mozilla/i.test(u) && !/(compati)/.test(u)) || (/opera/i.test(u))) {
document.addEventListener("DOMContentLoaded", i, false);
} else if (e) {
(function () {
var t = document.createElement('doc:rdy');
try {
t.doScroll('left');
i();
t = null;
} catch (e) {
st(arguments.callee, 0);
}
})();
} else {
window.onload = i;
}
})(init); //init is the function to call onload
I had the exact same issue that you had. I had a set of images that I wanted to ensure were preloaded before I began starting a slideshow. I was making use of
$(window).load(function(){
//All my code
});
And this is exactly what I was facing.
When I copied and pasted the URL in IE, the onload event did not seem to fire.
If I open the console using F12 and then past the URL in the browser and pressed enter, the everything seemed to be working.
Now that I opened the console at least once,
If I closeed the console and then reloaded the page, the onload was firing.
If I typed the URL and then pressed enter, the onload was firing.
It took me a couple of days to actually figure out what I was doing wrong.
The issue was with the console.log statements. At a lot of places in my code, I had done a lot of console logging. Even one of the plugins that I was using - jplayer has a an uncommented console message somewhere in the code.
The issue was that, unless you open the console at least once in IE, the console object is not available. Which means that the code will fail at the first console.log that it encounters.
Now, I was in no mood to comment out all my console.log statements just for the sake of testing it in IE. So, this is what I did instead. Right at the top of my document.ready jquery function, I wrote this small snippet of code.
if(!window.console){
console={};
console.log = function(){};
}
What it basically does is creates a dummy console.log function placeholder so that the code can run in IE but it will work only as long as console.log is the only console function that you are making use of in your code or in your plugins.
Just my 2 cents. Been pulling my hair over this issue for longer than I care to admit. I hope this is useful to at least someone.
You need to figure out if the code doesn't run at all, I.e. never enters your function, or if it fails on some specific line inside your function. Does IE9 show any warnings or js errors?
The easiest thing to do is stick a bunch of alert() statements in the code to see where it stops and narrow down to that line.
If it never enters your function then you need to look higher, where the call is being made.
Just a small note; When you use any debugging keywords (like console.log) or anything related, IE9 will escape this JS function if and only if the debugger is not on (with F12)
Actually I don't know what else cause a problem, but for me, my problem was the word "console.log" while debugger not on in IE9 ... I know this is already an answered question, but I felt it needs to be be known.
Okay, I figured it out. It has to do with some weird way IE handles IF statements.
In my init function I had two IF statements, one which checked if a variable existed and then logged the value of that variable. The other which checked to see if the value of the same variable was equal to an arbitrary string.
After removing the first IF statement, everything seems to work properly. I also decided to use a different onload function which can be seen below:
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', init, true);
} else if (document.all && !window.opera){ //Crude test for IE
//Define a "blank" external JavaScript tag
document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="javascript:void(0)"><\/script>');
var contentloadtag=document.getElementById("contentloadtag");
contentloadtag.onreadystatechange=function(){
if (this.readyState=="complete") {
init();
//ie('open');
}
}
}

Categories