繁体   English   中英

从Chrome扩展程序发送POST请求

[英]Send POST request from Chrome Extension

我正在编写一个Chrome扩展程序弹出窗口以登录到我的服务器。 该扩展名具有一个基本形式,带有usernamepasswordsubmit按钮。

<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/loginhttps://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!");
        }
    }
});

现在它可以按预期工作了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM