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;
5
  • 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. Commented Aug 26, 2019 at 19:59
  • @pcalkins i tried to add new div with id ="t" like this : ` + " document.body.innerHTML += '<div id = \"t\" style=\"display:none\">t</div>'; });"); ` but it is printing t as it is . i mean it is not printing value of "t" inside div Commented Aug 26, 2019 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 ..."<div id = 'var_for_selenium'>" + t + "</div>" You may want to build the string first for convenience. Then executeScript the string var. (For dealing with quotes...) Commented Aug 26, 2019 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. Commented Aug 26, 2019 at 21:33
  • @pcalkins i will try out and will let you know , i am sorry for late ack. Commented Aug 27, 2019 at 11:01

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.