The below code snippet is written using C# code in a normal UnitTest project template of Visual Studio. I have added the Selenium web driver support dlls by adding 2 NuGet packages : Selenium WebDriver Support classes and Selenium WebDriver. Then the below code is typed-in the Test method and the test is run in debug mode.
static IWebDriver driver;
driver = new ChromeDriver(@"C:\Selenium_Drivers"); // location of chromedriver.exe
driver.Url = "http://juliemr.github.io/protractor-demo/";
string javascript = "document.addEventListener('click', function(event){alert(event.relatedTarget);});";
((IJavaScriptExecutor)driver).ExecuteScript(javascript);
The code is excuted in debug mode and after the above 4 lines of code if we attempt to click on the loaded web page the alert window comes up with null value as shown below:
When the alert content in code is changed to show event.clientX
or any such properties from the list of properties described here - http://www.javascripture.com/MouseEvent
it is working well.
Can anyone suggest why only the relatedTarget
is returning null where we expect the element object to be present?
5Qe,
Firstly, as per documentation from javascripture, relatedTarget is not related to click but for mouseenter, mouseleave, dragenter etc.
Next, it seems that the event is directly added on the document, it is not working. If the same is done on an individual element, it would return the appropriate element.
This is what I tried -
string javascript = "document.getElementById('gobutton').addEventListener('mouseleave', function(event){alert(event.relatedTarget);});";
((IJavaScriptExecutor)driver).ExecuteScript(javascript);
and it is working.