2

In below code if the my div containing the attribute as text then only it will return the text. I am new/curious to find new way to use JavascriptExecutor instead of selenium as they are much faster than selenium

WebElement gettexxxt= driver.findElement(By.id("loginButton"));
JavascriptExecutor executor1 = (JavascriptExecutor) driver;
String text = (String) executor1.executeScript("return arguments[0].text;", gettexxxt));
System.out.println(text);

Right now I am retrieving the text as below using JavascriptExecutor

WebElement Rent_rentc =(WebElement) ((JavascriptExecutor) driver).executeScript("return document.getElementById('loginButton');");
System.out.println(Rent_rentc.getText());

Is there any way to get text using JavascriptExecutor except above solution?

Note:- I am editing this question as I got the answer of how to gettext from JavascriptExecutor by referring Vicky answer in this page. Please refer from here to answer my next problem that how we can perform drag and drop using JavascriptExecutor.

I am facing error in below code, Error :- No match found

    driver.get("https://jqueryui.com/droppable/");
    WebElement iframe=driver.findElement(By.xpath(".//*[@id='content']/iframe"));
    driver.switchTo().frame(iframe);
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

    try{  
      String filePath = "./dnd.js-master//dnd.js";
      String source = "div[id='draggable']";
      String target = "div[id='droppable']";
      StringBuffer buffer = new StringBuffer();
      String line;
      BufferedReader br = new BufferedReader(new FileReader(filePath));
      while((line = br.readLine())!=null)
          buffer.append(line);

      Pattern pattern = Pattern.compile("'(.*?)'");
      Matcher matcherSource = pattern.matcher(source);
      Matcher matcherTarget = pattern.matcher(target);
      String cssSource = "#" + matcherSource.group(1);
      String cssTarget = "#" + matcherTarget.group(1);

      String javaScript = buffer.toString();

      javaScript = javaScript + "$('" + cssSource + "').simulateDragDrop({ dropTarget: '" + cssTarget + "'});";
      ((JavascriptExecutor)driver).executeScript(javaScript);

    }
    catch(Exception ex)
    {
        System.out.println(ex.getMessage());
    }

Another code error :- expected expression, got '.'

    WebDriver driver = new FirefoxDriver();
    driver.manage().window().maximize();
    driver.get("https://jqueryui.com/droppable/");
     String line = null;
      String source = ".//*[@id='draggable']";
      String target = ".//*[@id='droppable']";
      try{
     BufferedReader br = new BufferedReader(new FileReader("./dnd.js-master//Drag.js"));
     StringBuffer buffer = new StringBuffer();
     while((line = br.readLine())!=null)
         buffer.append(line);

     String javaScript = buffer.toString();

     Thread.sleep(5000);//you can remove it added just to show you that drag and drop appeared as it is too fast

     String java_Script = javaScript + "$("+source+").simulateDragDrop({ dropTarget: "+target+"});";

     ((JavascriptExecutor)driver).executeScript(java_Script);
      }
            catch(Exception ex){
                System.out.println(ex.getMessage());
      }

}

Shubham Jain
  • 16,610
  • 15
  • 78
  • 125
  • You need to ask only one question per... question. You need to create a new question for the edit. If Vicky answered this question, please accept it as the answer so she gets credit for her work. – JeffC Aug 25 '15 at 17:52

1 Answers1

2

Use the below Javascript to get the text of the Element

String Rent_rentc =(String) ((JavascriptExecutor) driver).executeScript("return document.getElementById('loginButton').getElementsByTagName('div')[0].innerHTML;");

Also, I want to know can we perform drag and drop using JavascriptExecutor

A working example using the above javascript library is already posted in stackoverflow

Note:- I am editing this question as I got the answer of how to gettext from JavascriptExecutor by referring Vicky answer in this page. Please refer from here to answer my next problem that how we can perform drag and drop using JavascriptExecutor.

I am facing error in below code, Error :- No match found

EDIT :

(function ($) {
    $.fn.simulateDragDrop = function (options) {
        return this.each(function () {
            new $.simulateDragDrop(this, options);
        });
    };
    $.simulateDragDrop = function (elem, options) {
        this.options = options;
        this.simulateEvent(elem, options);
    };
    $.extend($.simulateDragDrop.prototype, {
        simulateEvent: function (elem, options) {
            /*Simulating drag start*/
            var type = 'dragstart';
            var event = this.createEvent(type);
            this.dispatchEvent(elem, type, event);

            /*Simulating drop*/
            type = 'drop';
            var dropEvent = this.createEvent(type, {});
            dropEvent.dataTransfer = event.dataTransfer;
            this.dispatchEvent($(options.dropTarget)[0], type, dropEvent);

            /*Simulating drag end*/
            type = 'dragend';
            var dragEndEvent = this.createEvent(type, {});
            dragEndEvent.dataTransfer = event.dataTransfer;
            this.dispatchEvent(elem, type, dragEndEvent);
        },
        createEvent: function (type) {
            var event = document.createEvent("CustomEvent");
            event.initCustomEvent(type, true, true, null);
            event.dataTransfer = {
                data: {
                },
                setData: function (type, val) {
                    this.data[type] = val;
                },
                getData: function (type) {
                    return this.data[type];
                }
            };
            return event;
        },
        dispatchEvent: function (elem, type, event) {
            if (elem.dispatchEvent) {
                elem.dispatchEvent(event);
            } else if (elem.fireEvent) {
                elem.fireEvent("on" + type, event);
            }
        }
    });

})(jQuery);

save the above jquery to a file ex:Drag.js

     driver.get("http://the-internet.herokuapp.com/drag_and_drop");
     String line = null;

     BufferedReader br = new BufferedReader(new FileReader("/path/Drag.js"));
     StringBuffer buffer = new StringBuffer();
     while((line = br.readLine())!=null)
         buffer.append(line);

     String javaScript = buffer.toString();

     Thread.sleep(5000);//you can remove it added just to show you that drag and drop appeared as it is too fast

     String java_Script = javaScript + "$('#column-a').simulateDragDrop({ dropTarget: '#column-b'});";

     ((JavascriptExecutor)driver).executeScript(java_Script);

}

please explain how it will work with the same div contain the or child div will contains many similar attribute like div

<button id="loginButton">Submit<button>

document.getElementById('loginButton') //will find the first element with id loginButton  

<a id="loginButton" class="initial" href="javascript:void(0)" onclick="pageController.submitForm(); return false;"><div>Login </div></a> <div>Login </div>

document.getElementById('loginButton').getElementsByTagName('div')[0]; //will find the first element with id loginButton and then first div child inside it

<a id="loginButton" class="initial" href="javascript:void(0)" onclick="pageController.submitForm(); return false;"><div>Login </div><div>Register</div></a>

 document.getElementById('loginButton').getElementsByTagName('div')[1]; //will find the first element with id loginButton and then second div child inside it

<a id="loginButton" class="initial" href="javascript:void(0)" onclick="pageController.submitForm(); return false;"><div><div>Register</div></div></a>

document.getElementById('loginButton').getElementsByTagName('div')[0].getElementsByTagName('div')[0].innerHTML;//will find the first element with id loginButton and then first div child inside it and then locate the first div child inside it

//you can also use other attributes like document.getElementsByClassName

Can you please provide me some links also where from I can refer/learn the formatting of the JavascriptExecutor

W3schools

Hope this helps you.Kindly get back if it is not working

Community
  • 1
  • 1
Vicky
  • 2,999
  • 2
  • 21
  • 36
  • I have tried with .innerHTML but it is giving me full stack of DOM. I just need the text from div. ..... Result I am getting after using .innerHTML is like this :-
    Continued
    – Shubham Jain Aug 25 '15 at 10:09
  • @Shubham jain pls post the html for that webelement – Vicky Aug 25 '15 at 10:13
  • @ShubhamJain Have edited the above code...checked it it is working fine.Kindly check and get back – Vicky Aug 25 '15 at 10:20
  • Yes @vijay you above code is working .. thanks .. but can you explain how is it working.. At next level I have tried it with next id if same page for the same div having that ID.. How you will get the text for same.. String Rent_rentc1 =(String) ((JavascriptExecutor) driver).executeScript("return document.getElementById('inProgressText').getElementsByTagName('div')[0].innerHTML;"); – Shubham Jain Aug 25 '15 at 11:40
  • Can you please provide me some links also where from I can refer/learn the formatting of the JavascriptExecutor – Shubham Jain Aug 25 '15 at 11:41
  • I have upvoted and thanks for your help .. please explain how it will work with the same div contain the or child div will contains many similar attribute like div – Shubham Jain Aug 25 '15 at 11:46
  • @ShubhamJain I have added some solutions for you regarding your query about locating same div and child div...Hav also added tutorials link for you.. – Vicky Aug 25 '15 at 12:29
  • -> Thanks I got the method for text revival from JavaScript. But still facing some issue with drag nd drop. I have edited my question and it have the code which I am using as your suggested URLs – Shubham Jain Aug 25 '15 at 12:57
  • I have added a solution.pls refer the above edit.I checked with the above solution it worked fine.Kindly check and get back – Vicky Aug 25 '15 at 13:49
  • No, Vicky .. It's give error like :- expected expression, got '.' .......... I had mention new code as you provided in question ... – Shubham Jain Aug 26 '15 at 04:48
  • Did you try with the above code or in different site...bcoz when i checked it worked for me – Vicky Aug 26 '15 at 04:52
  • 1
    Ok Vicky .. I will try same and get back to you soon. Thank you so much for your efforts, help and time. Appreciated – Shubham Jain Aug 26 '15 at 04:54