Warm tip: This article is reproduced from stackoverflow.com, please click
ajax google-chrome-extension javascript json

Chrome extension

发布于 2020-04-11 22:15:11

I'm trying to take text through a chrome extension and post them to google API.

At the moment I am receiving this error.

POST https://language.googleapis.com/v1/documents:analyzeSentiment?key=PASSWORD 400
Response {type: "cors", url: "https://language.googleapis.com/v1/documents:analy…iment?key=strongPassword", redirected: false, status: 400, ok: false, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 400
statusText: ""
type: "cors"
url: "https://language.googleapis.com/v1/documents:analyzeSentiment?key=Strongk"
__proto__: Response

I've tried using XMLHttpRequest instead of fetch, tested around with the code which is below (fetch used).

function sendData(text) {
    console.log(text);
// json p?
    var request = {
        document: {
            type: 'PLAIN_TEXT',
            content: text
        },
        encodingType: 'UTF8'
    };
    //use another type of call?
    var jsonRequest = JSON.stringify(request)
    console.log("JSON STRING: "+jsonRequest)
    fetch('https://language.googleapis.com/v1/documents:analyzeSentiment?key=StrongkPword', {
    mode:'cors',    
    method: 'POST',
        body: jsonRequest,
        headers: {
            'Content-Type': 'application/json'
        }
    }).then((res) => {
        console.log(res)
        console.log(res.body)
    });
}

So my current thoughts are, JsonP needs to be used, or there's something else not quite right.

The text being sent is

JSON STRING: {"document":{"type":"PLAIN_TEXT","content":"GIVE IT A STAB.. YEAH...PLZWORK "},"encodingType":"UTF8"}

{
    "manifest_version": 2,
    "name": "C.E",
    "short_name": "MRPHASMD",
    "version": "1.0",
    "author": "MICHAEL HOLBORN",

    "description": "A minimal extension which demonstrates ma power level.",

    "content_scripts": [
        {
            "matches": [ "*://mail.google.com/*" ],
            "js": [
                "src/extensionInjector.js"
            ],
            "run_at": "document_end"
        }
    ],

    "web_accessible_resources": [
        "dist/extension.js"
    ],

    "permissions": [
        "https://*/*"
    ]
}

I am quite confused as to how to get this working and appreciate your help!

Questioner
Michael Holborn
Viewed
25
Michael Holborn 2020-02-23 10:25

I solved this question by leveraging the chrome API to send messages to the background script function and then out to my API