我正在编写一个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客户端通过以下测试了服务器的响应:
URL:https://myserver.com/login
标题:Content-Type: application/x-www-form-urlencoded
表单网址已编码: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
请求的网址是Request URL: chrome-extension://ahlfehecmmmgbnpbfbokojepnogmajni/sign_in.html?
答案 0 :(得分:0)
因此,在进行一些挖掘之后,我发现在单击“提交”按钮后,该表单会重新加载弹出窗口,因此,在我有机会看到请求之前,它是令人耳目一新的。
作为解决方案,我必须通过如下编辑功能来禁用重新加载机制:
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!");
}
}
});
现在它可以正常工作了。