0

我正在尝试通过 javascript 执行器模拟锚标记上的右键单击事件。但收到错误“ReferenceError: OpenQA is not defined”。我不确定这是否是在 selenium 脚本中调用 JS 函数的正确方法。

IWebElement folderAtag = driver.FindElement(By.XPath("//[@title='folderA911536']"));          
 IJavaScriptExecutor js2 = ((IJavaScriptExecutor)driver);

      js2.ExecuteScript(
          "function contextMenuClick(element){" +

             "var evt = element.ownerDocument.createEvent('MouseEvents');" +

              "var RIGHT_CLICK_BUTTON_CODE = 2; " +

              " evt.initMouseEvent('contextmenu', true, true," +
              "  element.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, " +
              " false, false, false, RIGHT_CLICK_BUTTON_CODE, null); " +

              " if (document.createEventObject){ " +

                 "    return element.fireEvent('onclick', evt) " +
                 "  } " +
               " };" +
           "contextMenuClick(" + folderAtag + ");"
           );
4

1 回答 1

0

为了正确执行 js 代码,我使用 stringBuilder。例如下面:

public void jsClick(String key) throws IOException {
        JavascriptExecutor js = (JavascriptExecutor) driver;
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("var x = $(\'"+propertyKeysLoader(key) +"\');");
        stringBuilder.append("x.click();");
        js.executeScript(stringBuilder.toString());
    }

顺便说一句,鼠标右键单击我将以这种方式解决的元素:

WebElement elem = driver.findElement(By.xpath("//[@title='folderA911536']"));
new Actions(driver).contextClick(elem).perform();
于 2012-10-30T10:02:28.903 回答