1

Hello i am using Selenium with Java , trying to convert JavascriptExecutor inside script var to Java String . actually i have written a js method to get clicked element. I am trying to fetch clicked element's attribute .

Here is my Code :

    js.executeScript("document.body.addEventListener(\"click\", function (evt) {\n"
                    + "    console.dir(this);\n"
                    + "    //note evt.target can be a nested element, not the body element, resulting in misfires\n"
                    + "    var t = evt.target;\n"
                    + "    alert(t;\n"
                    + "});");`

i want to get alerted value 't' to Java String. like :

String ele = t;
  • I would consider inserting your own ID'd element containing "t" and then get the innerHTML. It'll be easier to get at since Unexpected Alert Behavior is a little odd for certain drivers right now. – pcalkins Aug 26 '19 at 19:59
  • @pcalkins i tried to add new div with id ="t" like this : ` + " document.body.innerHTML += '
    t
    '; });"); ` but it is printing t as it is . i mean it is not printing value of "t" inside div
    – Awais Arshad Aug 26 '19 at 20:27
  • you don't need to set the ID to t... just use something you reference in Selenium later... for the other t var, just close quotes, use +, and open again... like ..."
    " + t + "
    " You may want to build the string first for convenience. Then executeScript the string var. (For dealing with quotes...)
    – pcalkins Aug 26 '19 at 21:22
  • you might want to consider the purpose of this... Selenium will throw an exception if another element is going to retrieve the click so you could catch that kind of thing right there. – pcalkins Aug 26 '19 at 21:33
  • @pcalkins i will try out and will let you know , i am sorry for late ack. – Awais Arshad Aug 27 '19 at 11:01

0 Answers0