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