我正在编写一个 Chrome 扩展弹出窗口来登录我的服务器。扩展的基本形式为 username
, password
, 和 submit
按钮。
<form>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"
placeholder="Enter email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary btn-sm" id="loginButton">Log In</button>
</form>
我使用 Insomnia REST 客户端测试了我的服务器的响应,如下所示:
网址:
https://myserver.com/login
标题:Content-Type: application/x-www-form-urlencoded
表单 URL 编码:email: email@domain.com & password: password
在我的 Chrome 扩展程序上,我写了一个
signin.js
脚本来处理按钮单击事件并将请求发送到我的服务器。// hardcoded for simplicity of this example
const email = email@domain.com
const pwd = password
var button = document.getElementById("loginButton");
button.addEventListener("click", function(){
const req = new XMLHttpRequest();
const baseUrl = "https://myserver.com/login";
const urlParams = `email=${email}&password=${pwd}`;
req.open("POST", baseUrl, true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(urlParams);
req.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
console.log("Got response 200!");
}
}
});
然后在我的
manifest.json
文件,我有以下权限:"permissions": [
"storage",
"activeTab",
"cookies",
"*://*.myserver.com/*"
],
扩展加载并运行没有错误,但我在 DevTools 的网络选项卡上看不到请求。我可以看到所有文件都已加载,但没有对
myserver.com
的请求请求的 URL 是
Request URL: chrome-extension://ahlfehecmmmgbnpbfbokojepnogmajni/sign_in.html?
最佳答案
因此,经过一番挖掘,我发现表单在点击提交按钮后会重新加载弹出窗口,因此,在我有机会看到请求之前,它已经令人耳目一新。
作为一种解决方案,我必须通过如下编辑我的函数来禁用重新加载机制:
button.addEventListener("click", function(e){
e.preventDefault();
const req = new XMLHttpRequest();
const baseUrl = "https://myserver.com/login";
const urlParams = `email=${email}&password=${pwd}`;
req.open("POST", baseUrl, true);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(urlParams);
req.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
console.log("Got response 200!");
}
}
});
现在它按预期工作。
关于javascript - 从 Chrome 扩展发送 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56478681/