It works, but it’s not very useful, because I want to make an external
.js which contains all the JavaScript functions and call them from
there, not in a String.
您只能通过将外部js文件加载到DOM中来实现此目的
var addscript=window.document.createElement('script');addscript.type='text/javascript';addscript.src='http://localhost/somescript.js';document.getElementsByTagName('body')[0].appendChild(addscript);
注意:大多数浏览器不允许您加载本地资源,因此将外部js文件放在本地Web服务器中,然后像http://localhost/somescript.js一样访问它
将js文件加载到DOM后,您可以调用外部js文件中的javascript函数
例
假设我们有一个名为somescript.js的外部js文件,其中包含以下函数
//simple function which sets the value "test" to the search box
window.somefunc = function () {document.getElementsByName("s")[0].value='test';}
Webdriver代码:
driver.get("http://www.jquery.com");
//Load the External js file into DOM
((JavascriptExecutor) driver)
.executeScript("var addscript=window.document.createElement('script');addscript.type='text/javascript';addscript.src='http://localhost/somescript.js';document.getElementsByTagName('body')[0].appendChild(addscript);");
//wait for the js to be loaded to the DOM
((JavascriptExecutor) driver)
.executeScript("return typeof(somefunc)").toString().equals("function");
//Now you call the JavaScript functions in the JS file
((JavascriptExecutor) driver)
.executeScript("somefunc();");
注意:在幕后,Selenium将您的JavaScript代码包装在anonymous function中.因此,您的somefunc函数是此匿名函数的本地函数.由于JavaScript的作用域规则,somefunc不存在于该匿名函数之外.所以我们通过将它分配给窗口使它成为一个全局函数.
编辑:
And I don’t really understand why you use the window statement. And I
was searching something like ((JavascriptExecutor)
driver).executeScript(“here the .js”); But I don’t know if it is
possible
这是executeScript方法执行提供的javascript的方式
The script fragment provided will be executed as the body of an
anonymous function.
例如,如果我们使用以下代码
((JavascriptExecutor) driver)
.executeScript("somefunc = function () {document.getElementsByName("s")[0].value='test';}");
((JavascriptExecutor) driver)
.executeScript("somefunc();");
(function() {
somefunc = function () {document.getElementsByName("s")[0].value='test';}
})();
(function() {
somefunc();
});
What do you mean where you say that you want to put the external .js
into the DOM?
通过DOM我的意思是构建为对象树(简称你的网页)的页面的文档对象模型.我们使用javascript将外部js加载到网页,然后调用js文件中的函数并执行它们(就像在以上例子).
In the code that you put in your edit. Both functions are the same?
我刚才给出了一个例子,我的意思是执行脚本中提供的每个脚本都将在匿名函数的主体中执行.在我们的例子中,我们没有使用executioncript创建somefunc函数而是从外部js文件中使用它在dom中我们只使用executioncript方法调用它,所以你可以使用或不使用window对象
//simple function which sets the value "test" to the search box
somefunc = function () {document.getElementsByName("s")[0].value='test';}//this will also work
希望这会对你有所帮助.如果您有任何疑问,请回复.