首页 > 解决方案 > 从 chrome 扩展调用 API 的问题

问题描述

我正在尝试构建一个 chrome 扩展来制作内容脚本,我正在尝试进行 API 调用,但我无法得到响应。我收到类型 CORS 和状态 200 的响应。我已经将外部 API 主机附加到 manifest.json 的权限部分

我的代码是:

fetch('http://www.virustotal.com/vtapi/v2/ip-address/report?ip=8.8.8.8&apikey=My API KEY')
    .then(res => {
        console.log(res);
// Response{type: cors, url:http://www.virustotal.com/....... status: 200}
        return res.json(); // Here is the problem
    })
    .then(data => {
        console.log(data);
    })

清单.json:

{
    "name": "IP information on hover",
    "description": "IP information on hover",
    "version": "1.0",
    "manifest_version": 2,
    "browser_action": {
        "default_icon": "hello_extensions.png"
    },
    "permissions": [
        "https://www.virustotal.com/",
        "http://www.virustotal.com/"
    ],
    "content_scripts": [
        {
            "matches": [
                "http://*/*",
                "https://*/*"
            ],
            "js": [
                "jquery-3.4.0.js",
                "getIpReport.js"
            ],
            "run_at": "document_end"
        }
    ]
}

错误:未捕获(承诺中) SyntaxError:getIpReport.js:23 处 JSON 输入意外结束

标签: javascriptgoogle-chrome-extension

解决方案


内容脚本不能再发出跨域请求,请在后台脚本中进行,谢谢 wOxxOm


推荐阅读