簡體   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