How to click on an element generated by javascript with Watir? - javascript

I'm developing an jsf based application using a library called primefaces.
Primefaces generates a web page containing javascript functions that are generating some buttons. Buttons are not visible in the source code of the page (like < button>...< /button>, and so Watir can't click on these to test something.
My question is : is it possible to recover the id or class of button generated by a javascript function with Watir ?
Thanks

In practice, using sleep is not recommended. Depending on the amount of time the browser & JavaScript code takes to perform its action, you could run into race conditions and end up with tests that only work sometimes.
If you're considering using sleep, use wait_until instead. It will make your test code more resilient to timing issues in those cases where you really need to use it.
As #JustinKo recommended, you should probably be using Watir's wait methods to wait until the element is displayed on the page.
In your case, you'd want to try something like these examples:
# Assuming your browser object is named: $b
#Ex: $b = Watir::Browser.new :chrome
$b.button(:id => 'my_button').wait_until_present
Watir::Waiter::wait_until { $b.button(:id => 'my_button').visible? }
If you are having trouble finding the element on the page, you might want to look a the source code in FireBug or the Developer Tools console in Chrome (Shift+Ctrl+I). Try to find some identifying attribute for that button, or a container element with an id, class, name or some other identifying attribute.
However, at this time I'm not sure that there is a way to detect whether an element was generated or added to the DOM by JavaScript.

Related

Locating elements in Protractor vs directly in JavaScript

In one of the tests, I need to scroll into view of an element which can be done via scrollIntoView() method parameterizing the script with an element located via Protractor:
var elm = element(by.id("myid"));
browser.executeScript("arguments[0].scrollIntoView();", elm.getWebElement());
But, we can also find the element directly via getElementById():
browser.executeScript("document.getElementById('myid').scrollIntoView();");
What is the difference between the two approaches?
The scrollIntoView() is chosen for sample purposes only. The logic inside the script can be more complex.
The first one will tell you explicitly when the element is missing while the second one will raise a JavaScript error saying that null doesn't have the .scrollIntoView method. So to keep the second one maintainable, you need to implicitly handle the case when the element is missing and raise an error with an appropriate message.
The first one is exposed to an unexpected/stale state. The element found by element(by.id("myid")) could be removed from the page just before executing browser.executeScript(). The second one is not exposed to this issue since the page is not updated while the script is executed.
The second one is less expensive since it executes one Selenium command (ExecuteScript), while the first one executes two (FindElement and ExecuteScript). Sending a Selenium command to the browser is relatively expensive (minimum of 25ms) and might become significant with multiple calls.
Both will produce the exact same result and will end up calling the same API on the browser side.
A couple things come to mind.
Maintenance going forward. What happens if your .scrollIntoView() element locator changes? I think I would prefer finding the element using Selenium instead of JS. Reduced chance to have typos, type checking, and so on with an IDE but the IDE won't look into the string that contains your JS.
Selenium accessibility. Since Selenium can't see invisible elements, it could affect your choice either way. Would you want an exception to be thrown if you are trying to scroll to an invisible element? Selenium would let you know where JS wouldn't. Maybe you want to intentionally scroll to an invisible element. Finding invisible elements is a job for JS but not Selenium.
There may be more but this is all I can think of off the top of my head.

Finding out which Javascript methods are never called

I have a load of code, and I think much of it is deprecated with numerous methods that are never called. I would like to know which methods in this code will never be called, either as a result of button clicks or via other methods. I could go through and comment out the suspicious methods one-by-one and test the code, but is there a better way?
I am using Visual Studio 2012, and I have tried using JS Lint but that doesn't seem to tell me what I want to know. I really like the Code Analysis for C# and SQL that VS2012 does, but it doesn't do this for Javascript. What should I use?
Open your JS file as the script in a webpage in Chrome. Just surround your JS with an html and script tag:
<html><script>
var mycode = goeshere();
</script></html>
Once you open it in chrome, right click anywhere on the page and click 'Inspect Element'.
Alternatively you can just press CTRL+SHIFT+J to bring up the console.
Once the pane opens, click on the 'Profiles' tab.
Select "Collect JavaScript CPU Profile", and follow the steps to run it.
This will give you timing counts per function call. Try to work through as much of the functionality as you can, then once you are finished look at the function timing counts. Any call with 0 time probably wasn't called. This should at least give you a starting point.

How do I modify a browser tab's text styling with Javascript?

I am trying to write a bit of code in a script that changes the color and/or text formatting of a browser's tab--any tab, not just the currently selected one--when a given process completes, so that I can tell, without tabbing back to said tab, if the process is finished or not.
What I'm looking for is the specific bit of code or call to make that accesses the tab's style (or whatever); something where I could go
tabWhereScriptFinishedExecution.style.color("#77ffa5");
tabWhereScriptFinishedExecution.style.fontWeight("bold");
or something. Tab Mix Plus and its different effects on the tabs reflecting various states and whatnot were what got me thinking about this.
I'm using Firefox, and working this into a Greasemonkey script, so I'd like to avoid using JQuery if possible.
As far as I know it is not possible to do the way you are trying to achieve it. You cannot style the tab text. It is part of the browser. Tab Mix Plus you are referring to is a plug in for Firefox.

Is there a tool to analyze which javascript file added a certain portion of html / code?

When analyzing a webpage, I usually open these js files one after another and then read the source code to determine which file added a certain portion of html in the final rendered page. Is there an easy way / tool to solve this problem?
No, there is not a tool to do such a thing. Understanding the code yourself or searching for specific key phrases in the HTML you're trying to source (such as a class name or tag name or piece of text) is the typical method.
It could work to grep for the common ways that the DOM is modified (.innerHTML property, .appendChild(), .insertBefore, etc... if it's plain javascript) or similar methods in whatever library is being used.
Partially, you may use Firebug in Mozilla and, viewing the HTML tab, right click some tags and tick "break on child addition/removal". And then reload the page. Javascript execution will pause at any changing of DOM inside the chosen element.

unobtrusive Javascript, should I use it? what is the best way to manage and organize events? how do I prevent inefficiencies?

I have been struggling with choosing unobtrusive javascript over defining it within the html syntax. I want to convince my self to go the unobtrusive route, but I am having trouble getting past the issues listed below. Can you please help convince me :)
1) When you bind events unobtrusively, there is extra overhead on the client's machine to find that html element, where as when you do stuff, you don't have to iterate the DOM.
2) There is a lag between when events are bound using document.ready() (jquery) and when the page loads. This is more apparent on very large sites.
3) If you bind events (onclick etc) unobtrusively, there is no way of looking at the html code and knowing that there is an event bound to a particular class or id. This can become problematic when updating the markup and not realizing that you may be effecting javascript code. Is there a naming convention when defining css elements which are used to bind javascript events (i have seen ppl use js_className)
4) For a site, there are different pieces of javascript for different pages. For example Header.html contains a nav which triggers javascript events on all pages, where as homepage.html and searchPage.html contains elements that trigger javascript on their respective pages
sudo code example:
header.html
<script src="../myJS.js"></script>
<div>Header</div>
<ul>
<li>nav1</li><li>nav2</li>
</ul>
homepage.html
<#include header.html>
<div class="homepageDiv">some stuff</div>
searchpage.html
<#include header.html>
<div class="searchpageDiv">some other stuff</div>
myJS.js
$(document).ready(function(){
$("ul.li").bind("click",doSomething());
$(".homePageDiv").bind("click",doSomethingElse());
$(".searchPageDiv").bind("click",doSomethingSearchy());
});
In this case when you are on the searchPage it will still try to look for the "homepageDiv" which does not exist and fail. This will not effect the functionality but thats an additional unnecessary traversal. I could break this up into seperate javascript files, but then the browser has to download multiple files, and I can't just serve one file and have it cached for all pages.
What is the best way to use unobtrusive javascript so that I could easily maintain a ( pretty script heavy) website, so another developer is aware of scripts being bound to html elements when they are modifying my code. And serve the code so that the client's browser is not looking for elements which do not exist on a particular page (but may exist on others).
Thanks!
You are confused. Unobtrusive JavaScript is not just about defining event handlers in a program. It's a set of rules for writing JavaScript such that the script doesn't affect the functionality of other JavaScript on the same page. JavaScript is a dynamic language. Anyone can make changes to anything. Thus if two separate scripts on the same page both define a global variable add as follows, the last one to define it will win and affect the functionality of the first script.
// script 1
var add = function (a, b) {
return a + b;
};
// script 2
add = 5;
//script 1 again
add(2, 3); // error - add is a number, not a function
Now, to answer your question directly:
The extra overhead to find an element in JavaScript and attach an event listener to it is not a lot. You can use the new DOM method document.querySelector to find an element quickly and attach an event listener to it (it takes less than 1 ms to find the element).
If you want to attach your event listeners quickly, don't do it when your document content loads. Attach your event listeners at the end of the body section or directly after the part of your HTML code to which you wish to attach the event listener.
I don't see how altering the markup could affect the JavaScript in any manner. If you try to attach an event listener to an element that doesn't exist in JavaScript, it will silently fail or throw an exception. Either way, it really won't affect the functionality of the rest of the page. In addition, a HTML designer really doesn't need to know about the events attached any element. HTML is only supposed to be used for semantic markup; CSS is used for styling; and JavaScript is used for behavior. Don't mix up the three.
God has given us free will. Use it. JavaScript supports conditional execution. There are if statements. See if homePageDiv exists and only then attach an event listener to it.
Try:
$(document).ready(function () {
$("ul.li").bind("click",doSomething());
if (document.querySelector(".homePageDiv")) {
$(".homePageDiv").bind("click",doSomethingElse());
} else {
$(".searchPageDiv").bind("click",doSomethingSearchy());
}
});
Your question had very little to do with unobtrusive JavaScript. It showed a lack of research and understanding. Thus, I'm down voting it. Sorry.
Just because jQuery.ready() executes does not mean that the page is visible to the end user. This is a behaviour defined by browsers and these days there are really 2 events to take into consideration here as mootools puts it DomReady vs Load. When jQuery executes the ready method it's talking about the dom loading loaded however this doesn't mean the page is ready to be viewed by the user, external elements which as pictures and even style sheets etc may still be loading.
Any binding you do, even extremely inefficient ones will bind a lot faster than all the external resources being loaded by the browser so IMHO user should experience no difference between the page being displayed and functionality being made available.
As for finding binding on elements in your DOM. You are really just fearing that things will get lost. This has not really been my actual experience, more often than not in your JS you can check what page you are on and only add javascript for that page (as Aadit mentioned above). After that a quick find operation in your editor should help you find anything if stuff gets lost.
Keep in mind that under true MVC the functionality has to be separate from the presentation layer. This is exactly what OO javascript or unobtrusive javascript is about. You should be able to change your DOM without breaking the functionality of the page. Yes, if you change the css class and or element id on which you bind your JS will break, however the user will have no idea of this and the page will at least appear to work. However if this is a big concern you can use OO-Javascript and put div's or span's as placeholders in your dom and use these as markers to insert functionality or tell you that it exists, you can even use html comments. However, in my experience you know the behavior of your site and hence will always know that there is some JS there.
While I understand most of your concerns about useless traversals, I do think you are nickle and dime'ing it at this point if you are worried about 1 additional traversal. Previous to IE8 it used to be the case that traversing with the tag name and id was a lot faster than my selector but this is no longer true infact browsers have evolved to be much faster when using just the selectors:
$("a#myLink") - slowest.
$("a.myLink") - faster.
$("#Link") - fastest.
$(".myLink") - fastest.
In the link below you can see that as many as 34 thousand operations per second are being performed so I doubt speed is an issue.
You can use firebug to test the speed of each in the case of a very large dom.
In Summary:
a) Don't worry about losing js code there is always ctrl+f
b) There is no lag because dom ready does not mean the page is visible to start with.
Update
Fixed order of speed in operations based on the tests results from here
However keep in mind that performances of IE < 8 are really had if you don't specify the container (this used to be the rule, now it seems to be the exception to the rule).

Categories