【发布时间】:2019-01-03 19:31:27
【问题描述】:
我正在开发一个要求用户提供凭据的 Firefox 扩展程序,但我遇到了一个奇怪的问题。根据我在代码中放置 .send 调用的位置,代码是否执行网络请求。
这是manifest.json(主机名和域已被替换为假的):
{
"applications": {
"gecko": {
"id": "extension@example.com",
"strict_min_version": "58.0a1"
}
},
"browser_action": {
"browser_style": true,
"default_title": "Title",
"default_popup": "mowl.html"
},
"description": "Description",
"homepage_url": "https://example.com",
"manifest_version": 2,
"name": "Name",
"permissions": [
"*://www.example.com/*",
"tabs"
],
"content_security_policy": "script-src 'self' https://www.example.com; object-src 'self'",
"version": "1.0"
}
这是 HTML 弹出文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="mowl.js"></script>
</head>
<body>
Please login: <br><br>
<input type='email' placeholder='Email address:'' name='email' id='email' size='50'><br><br>
<input type='password' placeholder='Password' name='password' id='password' size='50'><br><br>
<button id="signin">Ok</button>
</body>
</html>
最后是javascript代码:
function processlogin() {
console.log('in processlogin');
if(http.readyState == 4) {
console.log(http.readyState);
}
}
function buttonClicked() {
document.querySelector('#signin').addEventListener('click', dologin, false);
}
function dologin () {
console.log('in dologin');
var website = "https://www.example.com/signin.php";
var params = "email=" + document.getElementById('email').value + "&password=" + document.getElementById('password').value;
http.open("POST", website);
http.responseType = 'text';
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = processlogin;
http.send(params);
}
document.addEventListener("DOMContentLoaded", buttonClicked);
var http = new XMLHttpRequest();
使用调试器在 Firefox 中测试该代码表明,单击按钮时根本不执行网络请求。我已将 console.log 语句放在不同的位置,以验证是否按预期调用了不同的函数。
但是,以这种方式修改 javascript:
function processlogin() {
console.log('in processlogin');
if(http.readyState == 4) {
console.log(http.readyState);
}
}
function buttonClicked() {
document.querySelector('#signin').addEventListener('click', dologin, false);
}
function dologin () {
console.log('in dologin');
}
document.addEventListener("DOMContentLoaded", buttonClicked);
var http = new XMLHttpRequest();
var website = "https://www.example.com/signin.php";
var params = "email=" + document.getElementById('email').value + "&password=" + document.getElementById('password').value;
http.open("POST", website);
http.responseType = 'text';
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = processlogin;
http.send(params);
执行网络调用(显然无需单击按钮)并在 Firefox 调试器中报告。我不明白发生了什么。
有人可以就我在这方面做错了什么提供一些指导吗?
非常感谢!
【问题讨论】:
-
在第二个版本中点击按钮时是否收到“In dologin”消息?
-
@Barmar:是的。我在第二个版本中收到了 dologin 消息。
标签: javascript xmlhttprequest firefox-addon