javascript
eclipse中java获取js的值_javascript – 如何在Eclipse中使用Selenium将外部.js导入我的Java测试?...
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
希望這會對你有所幫助.如果您有任何疑問,請回復.
總結
以上是生活随笔為你收集整理的eclipse中java获取js的值_javascript – 如何在Eclipse中使用Selenium将外部.js导入我的Java测试?...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java将数据封装为树结构_JAVA代码
- 下一篇: mini发布特别版车型,外观更加接近黑武