July 15, 2010 0

Adding JQuery Locators to Selenium

By Anthony in Selenium, Snippets, Test Automation, Testing

It’s very simple to add jquery functionality to your selenium installation, and also very useful if you use the functions a lot.

Add this to RemoteRunner.html

        <script language="JavaScript" type="text/javascript" src="lib/jquery.min.js"></script>
        <script language="JavaScript" type="text/javascript">
            function openDomViewer() {
                var autFrame = document.getElementById('selenium_myiframe');
                var autFrameDocument = new SeleniumFrame(autFrame).getDocument();
                this.rootDocument = autFrameDocument;
                var domViewer = window.open(getDocumentBase(document) + 'domviewer/domviewer.html');
                return false;
            }
        </script>

Next, for use in selenium we have to add the locator strategy to call functions:

mySelenium.addLocationStrategy("jquery",
            "var loc = locator; " +
            "var attr = null; " +
            "var isattr = false; " +
            "var inx = locator.lastIndexOf('@'); " +

            "if (inx != -1){ " +
            "   loc = locator.substring(0, inx); " +
            "   attr = locator.substring(inx + 1); " +
            "   isattr = true; " +
            "} " +

            "var found = jQuery(inDocument).find(loc); " +
            "if (found.length >= 1) { " +
            "   if (isattr) { " +
            "       return found[0].getAttribute(attr); " +
            "   } else { " +
            "       return found[0]; " +
            "   } " +
            "} else { " +
            "   return null; " +
            "}"
        );

To use the newly created functionality:

jquery=