Dav*_*ook 20 javascript google-chrome-extension typescript webpack axios
我正在构建一个 chrome 扩展,当从内容脚本收到某些消息时,该扩展需要进行 API 调用。我在发出 HTTP 请求时遇到困难,我相信我的 webpack 配置是罪魁祸首。
我尝试过使用node-fetchand axios,但都不适合我。
我的 webpack.common.js 文件如下所示:
const path = require("path");
module.exports = {
target: "node",
entry: {
popup: path.join(__dirname, "src/popup/index.tsx"),
background: path.join(__dirname, "src/background.ts"),
contentScript: path.join(__dirname, "src/contentScript.ts"),
},
output: {
path: path.join(__dirname, "dist"),
filename: "[name].js",
},
module: {
rules: [
{
exclude: /node_modules/,
test: /\.tsx?$/,
use: "ts-loader",
},
{
exclude: /node_modules/,
test: /\.scss$/,
use: [
{
loader: "style-loader", // Creates style nodes from JS strings
},
{
loader: "css-loader", // Translates CSS into CommonJS
},
{
loader: "sass-loader", // Compiles Sass to CSS
},
],
},
],
},
resolve: {
extensions: [".ts", ".tsx", ".js"],
},
};
Run Code Online (Sandbox Code Playgroud)
当脚本尝试从 chrome 扩展程序调用 axios 时,我收到以下错误:
dispatchRequest.js:52 Uncaught (in promise) TypeError: adapter is not a function
at dispatchRequest (dispatchRequest.js:52)
Run Code Online (Sandbox Code Playgroud)
pie*_*dra 21
我好像晚了 10 个月,但这对于遇到同样问题的人来说可能很有用。从 Axios 迁移到 fetch 可能是一个不错的选择,但如果您在 Axios 及其所有实用程序(拦截器、取消等)之上构建了自定义 API,则工作量很大,因此有一个简单的修复方法:
Axios 在其配置中接受适配器字段,因此您可以传递像axios-fetch-adapter这样的获取适配器,并且可能您还需要添加regenerator-runtime,因此在您的 background.js 文件中:
import "regenerator-runtime/runtime.js";
Run Code Online (Sandbox Code Playgroud)
小智 11
我遇到了类似的问题。我认为在 chrome 扩展的 Service Worker 上使用 axios 时会发生这种情况。
当访问其他来源并在 chrome 扩展的 Service Worker 上获取响应(即 CROS)时,我可以通过执行以下操作来请求它们
首先,你不能在Service Worker上使用axios。axios 在获取适配器时尝试使用 xhr 和 http,但不能在 Service Worker 上同时使用这两者。所以,使用fetch,应该是cros模式。
要在 cros 模式下使用 fetch,请将目标 URL 放入 host_permissions 中。我在其他网站上看到过权限中 URL 的示例,但如果不使用 host_permissions,则会出现错误。
实际代码应如下所示。(部分摘录)
清单.json
"background": {
"service_worker": "background.js"
},
"host_permissions": ["https://sample.com/*"]
Run Code Online (Sandbox Code Playgroud)
背景.js
const res = await fetch(baseUrl + word, {
method: "GET",
mode: "cors",
});
const txt = await res.text();
Run Code Online (Sandbox Code Playgroud)
我在下面写了更详细的项目历史,希望你在翻译时看一下。
https://takumi-oda.com/blog/2021/09/30/post-2006/
| 归档时间: |
|
| 查看次数: |
18892 次 |
| 最近记录: |