[英]XMLHttpRequest status 0 in click event handler
I'm writing a Google Chrome extension to take advantage of an API we have written. 我正在编写Google Chrome扩展程序,以利用我们编写的API。 The problem I'm having is that the popup.html has a login form, and when the submit button is pressed it calls the necessary authentication code, which involves making a couple of XMLHttpRequests to the API server. 我遇到的问题是popup.html具有登录表单,并且当按下“提交”按钮时,它会调用必要的身份验证代码,其中包括向API服务器发送几个XMLHttpRequest。
The code is as follows: 代码如下:
authenticate.js authenticate.js
function authenticate(username, password)
{
var xhr = new XMLHttpRequest();
xhr.open("GET", "<api-server>/challenge?username=dummyusername", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
alert(xhr.status);
}
};
xhr.send();
}
/*Gets the username and password textboxes from popup.html and passes their values on to authenticate()*/
function getCredentials()
{
authenticate("test", "test");
}
document.addEventListener("DOMContentLoaded", function() {
var submitBtn = document.getElementById("submitBtn");
if (submitBtn != null) {
submitBtn.onclick = getCredentials;
}
});
popup.html popup.html
<!doctype html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<form>
<label for="username">Username:</label>
<input type="text" id="usernameTxt"><br>
<label for="password">Password:</label>
<input type="password" id="passwordTxt"><br><br>
<input type="submit" id="submitBtn" value="Submit">
</form>
<script src="authenticate.js"></script>
</body>
</html>
manifest.json manifest.json
{
"manifest_version": 2,
"name": "Chrome Extension",
"description": "Chrome Extension",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"tabs",
"<all_urls>",
"activeTab",
"https://ajax.googleapis.com/",
"<api-server>"
]
}
If, however, I replace: 但是,如果我替换:
document.addEventListener("DOMContentLoaded", function() {
var submitBtn = document.getElementById("submitBtn");
if (submitBtn != null) {
submitBtn.onclick = getCredentials;
}
});
with: 与:
document.addEventListener('DOMContentLoaded', function() {
getCredentials();
});
it does the right thing, which leads me to believe it's to do with the fact that it's being called from a click event handler and perhaps somehow the permissions haven't been extended to the button. 它做的是正确的,这使我相信这与以下事实有关:从单击事件处理程序中调用了它,也许还没有将权限扩展到按钮。
I saw this post ( Chrome Extension: XMLHttpRequest canceled (status == 0) ) and added "<all_urls>"
to permissions and that has made no difference. 我看到了这篇文章( Chrome扩展:XMLHttpRequest已取消(状态== 0) ),并向权限添加了"<all_urls>"
,这没有任何区别。
Cancel the click so the form does not submit. 取消点击,使表单不提交。
document.getElementById("submitBtn").addEventListener('click', function(evt){
evt.preventDefault();
getCredentials();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.