Chrome扩展程序通过POST将所选文本发送到外部API

时间:2018-05-20 11:27:39

标签: javascript google-chrome google-chrome-extension

这是我的popup.js文件

chrome.tabs.executeScript( {
    code: "window.getSelection().toString();"
}, function(selection) {
    document.getElementById("output").innerHTML = selection[0];
});

如何通过POST请求将所选文本与网址一起发送到外部API?

1 个答案:

答案 0 :(得分:0)

以下代码能够将POST请求发送到外部API

<强> popup.js:

chrome.tabs.executeScript( {
    code: "window.getSelection().toString();"
}, function(selection) {
    //document.getElementById("output").innerHTML = selection[0];
    var data = "quote=This%20is%20%dope%20feature%20with%20embed%20option";

    var xhr = new XMLHttpRequest();
    xhr.withCredentials = true;

    xhr.addEventListener("readystatechange", function () {
      if (this.readyState === 4) {
        console.log(this.responseText);
      }
    });

    xhr.open("POST", "http://localhost:8000/api/excerpt/");
    xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("authorization", "Token 42f2909aeacc293ac3a33a76485821e6399d5e1472");

    xhr.send(data);    
});