2015-11-14 77 views
0

我試圖爲我的同事創建一個html文檔來完成在線測試(我有正確的答案)。當文檔加載時,它會請求您的用戶和密碼並嘗試登錄,然後填寫答案並提交。Javascript:使用while循環等待文檔加載不起作用

但是我無法通過用戶名和密碼值,在頁面中的元素,這是錯誤:

Cannot set property 'value' of null

頁面沒有完全加載時,我的腳本試圖獲得其元素,我怎麼能做這個工作?

<html> 
<head> 
    <title>BCG test</title> 
    <script type="text/javascript"> 
     function bcg(){ 
      var user = prompt("Enter username: "); 
      var pass = prompt("Enter password: "); 
      var site = "http://app.huawei.com/bcg"; 

      location = site; 

      while(true){ 
       if (document.readyState == "complete"){ 
        break; 
       } 
      } 

      var user_box = document.getElementById("uid"); 
      var pass_box = document.getElementById("password"); 
      var submit_button = document.getElementsByName("Submit")[0]; 

      user_box.value = user; 
      pass_box.value = pass; 
      submit_button.click(); 
     } 

    </script> 
</head> 
<body onload = "bcg()"> 
    <h1>BCG TEST</h1> 
</body> 
</html> 
+0

您無法與其他網頁上的內容進行互動,就像您正在嘗試的那樣。當您更改「位置」並開始導航時,在下一頁加載之前,當前頁面的內容(包括其中的所有JavaScript)被刪除。如果您想模仿用戶,請查看[無頭瀏覽器](https://en.wikipedia.org/wiki/Headless_browser)。 –

回答

1

你不應該使用while(true)循環,因爲無限循環快,永遠。這會導致瀏覽器凍結。如果您需要繼續檢查某些內容,請使用setInterval設置一個計時器。

但是,爲此,您似乎希望等待頁面加載。把你的代碼在此塊代爲執行:

document.addEventListener("DOMContentLoaded", function() { 
     var user_box = document.getElementById("uid"); 
     var pass_box = document.getElementById("password"); 
     var submit_button = document.getElementsByName("Submit")[0]; 

     user_box.value = user; 
     pass_box.value = pass; 
     submit_button.click(); 
}); 
0

你不能這樣做,在javascript:

while(true){if(document.readyState == "complete"){ break; }} 

它永遠不會退出這一事件框架。

使用window.onload = function(){}$(document).ready(function(){})

所有這些功能將被調用時加載文檔。