通过WebDriver在C#中执行Javascript文件
我试图通过C#中的webdriver执行一个javascript文件。以下是我目前掌握的情况:通过WebDriver在C#中执行Javascript文件,javascript,c#,selenium-webdriver,Javascript,C#,Selenium Webdriver,我试图通过C#中的webdriver执行一个javascript文件。以下是我目前掌握的情况: IJavaScriptExecutor js = driver as IJavaScriptExecutor; (string)js.ExecuteScript("var s = window.document.createElement(\'script\'); s.src = \'E:\\workspace\\test\\jsPopup.js\'; window.document.head.app
IJavaScriptExecutor js = driver as IJavaScriptExecutor;
(string)js.ExecuteScript("var s = window.document.createElement(\'script\'); s.src = \'E:\\workspace\\test\\jsPopup.js\'; window.document.head.appendChild(s); ");
js.ExecuteScript("return ourFunction");
jsfile.js的内容如下
document.ourFunction = function(){ tabUrl = window.location.href;
imagesPath = chrome.extension.getURL("images");
var optionsPopupPath = chrome.extension.getURL("options.html");
}
但是当我执行
js.ExecuteScript("return ourFunction");
它抛出一个找不到的函数异常。我想做的是通过js注入或任何其他方法运行一个完整的javascript文件,让我访问js文件生成的数据。有什么帮助吗 这里有三个问题:
ourFunction()
,而不是ourFunction
,否则您将得到一个与Uncaught ReferenceError:ourFunction没有定义(…)
ourFunction
被添加到document
而不是全局范围,因此您需要document.ourFunction()
,否则您将得到相同的错误undefined
。如果您试图返回它的“值”,您将在浏览器中得到类似于Uncaught SyntaxError:invally return statement(…)
的内容,或者可能在代码中返回null
document.ourFunction = function(){ tabUrl = window.location.href;
imagesPath = chrome.extension.getURL("images");
var optionsPopupPath = chrome.extension.getURL("options.html");
return optionsPopupPath; // return here!
}
然后js.ExecuteScript(“returndocument.ourFunction()”代码>应该工作
更新:
(您可以尝试:js.ExecuteScript(“return document.ourFunction();”);
(添加分号),但这不会有什么区别。)
我建议(除了添加return
语句外)暂时注释掉chrome.extension
行,以防它们抛出错误并导致函数无法创建。我认为这是最有可能失败的原因
这样做之后,我在Firefox和Chrome中就可以很好地使用它,而无需任何显式或隐式的等待。我从未使用过selenium,因此,如果这是一个哑巴,我深表歉意,但我希望您需要包括以下参数:js.ExecuteScript(“return ourFunction()”代码>我不认为这是导致异常的原因。我正在关注,作者似乎也不介意()。添加行var path=js.ExecuteScript(“return document.ourFunction()”;引发以下异常[代码]WebDriver.dll中发生类型为“System.InvalidOperationException”的未处理异常其他信息:未知错误:document.ourFunction不是函数。但是,下面的行可以工作。var path=js.ExecuteScript(“return document.ourFunction”);但它仍然在路径中生成null。我已将jsPopup.js函数更改为包含return语句。稍后我将对此进行更详细的尝试。我认为您对()注释和其他内容的看法是正确的,因为我刚刚发现我的javascript根本没有加载。到目前为止,在我检查chrome inspector中的web元素时,它似乎试图使文件路径成为web url的扩展名。因此javascript不会被加载。因此,ourFunction()不返回此类函数。我添加了以下行来检查var test=js.ExecuteScript(“returntypeof(ourFunction)”);返回未定义的。