我正在编写一个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
表单URL编码:email: [email protected] & password: password
在我的Chrome扩展程序中,我编写了一个signin.js
脚本来处理按钮单击事件,并将请求发送到我的服务器。
// hardcoded for simplicity of this example
const email = [email protected]
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?
因此,经过一番挖掘,我发现在单击“提交”按钮后,该表单会重新加载弹出窗口,因此,在我有机会看到请求之前,它是令人耳目一新的。
作为解决方案,我必须通过如下编辑函数来禁用重载机制:
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!");
}
}
});
现在它可以按预期工作了。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句