温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - Chrome extension
ajax google-chrome-extension javascript json

javascript - Chrome扩展程序

发布于 2020-04-12 00:20:00

我正在尝试通过chrome扩展程序获取文本并将其发布到google API。

目前,我收到此错误。

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

我尝试使用XMLHttpRequest而不是fetch,并在下面的代码(使用fetch)中进行了测试。

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)
    });
}

所以我目前的想法是,需要使用JsonP,否则还有其他不正确的事情。

正在发送的文本是

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://*/*"
    ]
}

我很困惑如何使它正常工作并感谢您的帮助!

查看更多

提问者
Michael Holborn
被浏览
52
Michael Holborn 2020-02-23 10:25

我通过利用chrome API将消息发送到后台脚本功能,然后发送到我的API来解决了这个问题