使用IJavaScriptExecutor时如何挂钩自定义javascript触发器

时间:2017-07-05 16:51:33

标签: javascript c# selenium protractor

我们在Web应用程序中定义了此事件,它创建了一个名为timelineEventClicked

的自定义触发器
canvas.addEventListener('click', function (evt) {
                    evt.stopImmediatePropagation();
                    var mousePos = getMousePos(canvas, evt);

                        ...//some manipulation here

                        $.event.trigger({
                            type: "timelineEventClicked",
                            sender: _timelineObject,
                            events: settings.events,
                            eventData: eventData
                        });
                    });

我想挂钩此事件timelineEventClicked并通过注入

使用selenium或量角器返回eventData
IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;
 executor.ExecuteScript(@"(function() {                       
                    document.addEventListener('timelineEventClicked', function(e) {
                        //Not sure what to do here to get back evendata
                })();"
                );

问题在于它似乎无法识别事件timelineEventClicked并且不确定原因。

1 个答案:

答案 0 :(得分:1)

要检索事件,请使用侦听器将其存储在全局范围内。 然后单击画布以触发事件并返回变量:

IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;

// install the listener
executor.ExecuteScript(
  "$(document).on('timelineEventClicked', function(e){ window._evt=e; });");

// trigger the event
driver.FindElement(...).Click();

// return the event
var data = executor.ExecuteScript(@"return window._evt;");