单击事件处理程序中的XMLHttpRequest状态0

时间:2015-12-01 14:27:21

标签: javascript google-chrome google-chrome-extension xmlhttprequest

我正在编写Google Chrome扩展程序,以利用我们编写的API。我遇到的问题是popup.html有一个登录表单,当按下提交按钮时,它会调用必要的身份验证代码,这涉及到API服务器发出一些XMLHttpRequests。

代码如下:

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>"
  ]
}

但是,如果我更换:

document.addEventListener("DOMContentLoaded", function() {
  var submitBtn = document.getElementById("submitBtn");
  if (submitBtn != null) {
    submitBtn.onclick = getCredentials;
  }
});

使用:

document.addEventListener('DOMContentLoaded', function() {
  getCredentials();
});

它做了正确的事情,这使我相信它是从点击事件处理程序调用它的事实,也许某种程度上权限尚未被扩展到按钮。

我看到了这篇帖子(Chrome Extension: XMLHttpRequest canceled (status == 0))并将"<all_urls>"添加到了权限中,这没有任何区别。

1 个答案:

答案 0 :(得分:2)

取消点击,以便表单不会提交。

document.getElementById("submitBtn").addEventListener('click', function(evt){
    evt.preventDefault();
    getCredentials();
});