Reputation: 173
I'm writing a Google Chrome extension to take advantage of an API we have written. 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.
The code is as follows:
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
<!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_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.
Upvotes: 0
Views: 97
Reputation: 207501
Cancel the click so the form does not submit.
document.getElementById("submitBtn").addEventListener('click', function(evt){
evt.preventDefault();
getCredentials();
});
Upvotes: 2