# @capacitor-community/barcode-scanner 中文文档

规范地址：https://npmcn.com/package/%40capacitor-community/barcode-scanner/

版本：4\.0\.1
npm 元数据更新时间：2026-10-23T21:47:41.559Z
中文译文更新时间：2026-11-09T03:23:47.260Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40capacitor-community/barcode-scanner
原文对照：https://npmcn.com/package/%40capacitor-community/barcode-scanner/?lang=original
项目主页：https://github.com/capacitor-community/barcode-scanner#readme
源码仓库：https://github.com/capacitor-community/barcode-scanner

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：172 kB，44 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：2 个
- peer 依赖：@capacitor/core ^5\.0\.0
- 首次发布：2021-03-16T15:44:15.237Z
- 最新版本发布：2023-05-08T19:24:11.405Z
- 近 30 天下载量：51088（2026-10-09 至 2026-11-07，npm 官方下载统计）
- 已发布版本数：18（近 12 个月 0 个）

## 中文简介

快速而高效的Capacitor(QR)条码扫描仪

## 安装

```sh
npm install @capacitor-community/barcode-scanner
```

也可以使用：`pnpm add @capacitor-community/barcode-scanner`、`yarn add @capacitor-community/barcode-scanner`、`bun add @capacitor-community/barcode-scanner`

## README

  
![](https://user-images.githubusercontent.com/236501/85893648-1c92e880-b7a8-11ea-926d-95355b8175c7.png)

### 条形码扫描器

**`@capacitor-community/barcode-scanner`**

快速高效(QR)条码扫描仪用于Capacitor.

![](https://img.shields.io/maintenance/yes/2022?style=flat-square) [![](https://img.shields.io/npm/l/@capacitor-community/barcode-scanner?style=flat-square)](https://www.npmjs.com/package/@capacitor-community/barcode-scanner)  
[![](https://img.shields.io/npm/dw/@capacitor-community/barcode-scanner?style=flat-square)](https://www.npmjs.com/package/@capacitor-community/barcode-scanner) [![](https://img.shields.io/npm/v/@capacitor-community/barcode-scanner?style=flat-square)](https://www.npmjs.com/package/@capacitor-community/barcode-scanner) [![](https://img.shields.io/badge/all%20contributors-1-orange?style=flat-square)](https://npmcn.com/package/%40capacitor-community/barcode-scanner/#readme-contributors-)

## 目录

-   [维护者](https://npmcn.com/package/%40capacitor-community/barcode-scanner/#readme-maintainers)
-   [关于](https://npmcn.com/package/%40capacitor-community/barcode-scanner/#readme-about)
-   [安装](https://npmcn.com/package/%40capacitor-community/barcode-scanner/#readme-installation)
-   [使用量](https://npmcn.com/package/%40capacitor-community/barcode-scanner/#readme-usage)
-   [解决问题](https://npmcn.com/package/%40capacitor-community/barcode-scanner/#readme-troubleshooting)

## 维护者

| 维护者 | GitHub 图像 | 活动 |
| --- | --- | --- |
| 语录 | [语录](https://github.com/thegnuu) | 对 |
| 泰法尔 | [泰法尔](https://github.com/tafelnl) | 没有 |

## 关于

### 支持的条码

打开 **iOS系统** 这个库使用苹果自己的 `AVFoundation`。这意味着 **[此条码列表](https://developer.apple.com/documentation/avfoundation/avmetadatamachinereadablecodeobject/machine-readable_object_types)** 应支持.

打开 **机器人** 此库使用 [`zxing-android-embedded`](https://github.com/journeyapps/zxing-android-embedded) 用于 [`zxing`](https://github.com/zxing/zxing) 在引擎盖下。 这意味着 **[此条码列表](https://github.com/zxing/zxing/#supported-formats)** 被支持.

打开 **网页** 此库使用 [`zxing/browser`](https://github.com/zxing-js/browser)这意味着 **[此条码列表](https://github.com/zxing/zxing/#supported-formats)** 被支持。 网络实施正在进行中,可能存在问题,并非所有功能目前都得到支持!

### 关于所支持的电容版本的说明

`v5.x.x-beta.x` 基于支持Capacitor的ML-Kit的预发 `v5.x`

`v4.x` 支持电容 `v5.x`

`v3.x` 支持电容 `v4.x`

`v2.x` 支持电容 `v3.x`

`v1.x` 支持电容 `v2.x`

此软件包的所有发布都可以在 [无](https://www.npmjs.com/package/@capacitor-community/barcode-scanner?activeTab=versions) 继续 [GitHub 发布](https://github.com/capacitor-community/barcode-scanner/releases)

## 安装

```bash
npm install @capacitor-community/barcode-scanner
npx cap sync
```

### iOS系统

对于iOS,您需要在您的信息.plist文件中设置使用描述.

可以通过直接将其添加到源代码中或通过使用Xcode财产清单检查员来做到这一点.

**直接添加到源代码**

1.  打开Info.plist(用 Xcode 右键点击 > Open As > source 代码)
2.  与 `<dict></dict>` 更改如下:

```diff
<dict>
+  <key>NSCameraUsageDescription</key>
+  <string>To be able to scan barcodes</string>
</dict>
```

_注:_ "能够扫描条码"可以被任意替换.

**使用 Xcode 属性列表检查器添加**

1.  打开Info.plist **xcode 编码** (右键单击 > 打开为 > 属性列表)
2.  在“信息属性列表”下点击小项 `+` 按钮.
3.  下 `key`,键入“隐私-相机使用描述”
4.  下 `value`,键入“能够扫描条码”

_注:_ "能够扫描条码"可以被任意替换.

这里的更多信息 : [https://developer.apple.com/documentation/bundleresources/information property list/nscamerausagepescription 互联网档案馆的存檔,存档日期2013-12-02](https://developer.apple.com/documentation/bundleresources/information_property_list/nscamerausagedescription)

### 机器人

在你体内 `AndroidManifest.xml` 文件,修改如下:

```diff
<?xml version="1.0" encoding="utf-8"?>
<manifest
  xmlns:android="http://schemas.android.com/apk/res/android"
+  xmlns:tools="http://schemas.android.com/tools"
  package="com.example">

  <application
+    android:hardwareAccelerated="true"
  >
  </application>

+  <uses-permission android:name="android.permission.CAMERA" />

+  <uses-sdk tools:overrideLibrary="com.google.zxing.client.android" />
</manifest>
```

## 使用量

可找到完整的 API 引用 [这里](https://npmcn.com/package/%40capacitor-community/barcode-scanner/src/definitions.ts)。 。 。 .

扫描一个(QR)条码可以简单如:

```js
import { BarcodeScanner } from '@capacitor-community/barcode-scanner';

const startScan = async () => {
  // Check camera permission
  // This is just a simple example, check out the better checks below
  await BarcodeScanner.checkPermission({ force: true });

  // make background of WebView transparent
  // note: if you are using ionic this might not be enough, check below
  BarcodeScanner.hideBackground();

  const result = await BarcodeScanner.startScan(); // start scanning and wait for a result

  // if the result has content
  if (result.hasContent) {
    console.log(result.content); // log the raw scanned content
  }
};
```

### 网络视频不透明

`hideBackground()` 将实现 `<html>` 内容透明,通过添加 `background: 'transparent';` 页:1 `style` 属性.

如果您正在使用Ionic, 您也需要设置一些 Css 变量, 请检查 [**这里**](https://npmcn.com/package/%40capacitor-community/barcode-scanner/#readme-ionic-css-variables)

如果您仍然无法看到相机视图, 请检查 [**这里**](https://npmcn.com/package/%40capacitor-community/barcode-scanner/#readme-the-scanner-view-does-not-show-up)

### 停止扫描

之后 `startScan()` 解析后,扫描视图将自动被销毁以保存电池。 但是,如果你想取消扫描之前 `startScan()` 已解决(AKA尚未识别代码),您必须拨打 `stopScan()` 手动. 示例

```js
import { BarcodeScanner } from '@capacitor-community/barcode-scanner';

const stopScan = () => {
  BarcodeScanner.showBackground();
  BarcodeScanner.stopScan();
};
```

考虑用户点击某种后键(硬件或软件)的情况也很重要. 建议打电话 `stopScan()` 在这类情况中也是如此.

在Vue.js中,你可以在使用扫描仪的特定视图中做这样的事情:

```vue
<script>
import { BarcodeScanner } from '@capacitor-community/barcode-scanner';

export default {
  methods: {
    stopScan() {
      BarcodeScanner.showBackground();
      BarcodeScanner.stopScan();
    },
  },

  deactivated() {
    this.stopScan();
  },

  beforeDestroy() {
    this.stopScan();
  },
};
</script>
```

### 正在准备扫描

提高性能和反应能力(略微),a `prepare()` 方法可用。 如果你知道你的剧本会打电话 `startScan()` 不久,你可以打电话 `prepare()` 将制作 `startScan()` 工作更快一点.

例如:

```js
import { BarcodeScanner } from '@capacitor-community/barcode-scanner';

const prepare = () => {
  BarcodeScanner.prepare();
};

const startScan = async () => {
  BarcodeScanner.hideBackground();
  const result = await BarcodeScanner.startScan();
  if (result.hasContent) {
    console.log(result.content);
  }
};

const stopScan = () => {
  BarcodeScanner.showBackground();
  BarcodeScanner.stopScan();
};

const askUser = () => {
  prepare();

  const c = confirm('Do you want to scan a barcode?');

  if (c) {
    startScan();
  } else {
    stopScan();
  }
};

askUser();
```

这是完全可选的,将同:

```js
import { BarcodeScanner } from '@capacitor-community/barcode-scanner';

const startScan = async () => {
  BarcodeScanner.hideBackground();
  const result = await BarcodeScanner.startScan();
  if (result.hasContent) {
    console.log(result.content);
  }
};

const askUser = () => {
  const c = confirm('Do you want to scan a barcode?');

  if (c) {
    startScan();
  }
};

askUser();
```

后者在用户看来会稍慢一些.

### 权限

此插件不会自动处理权限 。 不过插件 _已经_ 拥有检查和请求许可的实用方法。 您必须请求 JavaScript 的许可 。 下面是一个简单的例子:

```js
import { BarcodeScanner } from '@capacitor-community/barcode-scanner';

const checkPermission = async () => {
  // check or request permission
  const status = await BarcodeScanner.checkPermission({ force: true });

  if (status.granted) {
    // the user granted permission
    return true;
  }

  return false;
};
```

一个更详细、更能优化UX的例子:

```js
import { BarcodeScanner } from '@capacitor-community/barcode-scanner';

const didUserGrantPermission = async () => {
  // check if user already granted permission
  const status = await BarcodeScanner.checkPermission({ force: false });

  if (status.granted) {
    // user granted permission
    return true;
  }

  if (status.denied) {
    // user denied permission
    return false;
  }

  if (status.asked) {
    // system requested the user for permission during this call
    // only possible when force set to true
  }

  if (status.neverAsked) {
    // user has not been requested this permission before
    // it is advised to show the user some sort of prompt
    // this way you will not waste your only chance to ask for the permission
    const c = confirm('We need your permission to use your camera to be able to scan barcodes');
    if (!c) {
      return false;
    }
  }

  if (status.restricted || status.unknown) {
    // ios only
    // probably means the permission has been denied
    return false;
  }

  // user has not denied permission
  // but the user also has not yet granted the permission
  // so request it
  const statusRequest = await BarcodeScanner.checkPermission({ force: true });

  if (statusRequest.asked) {
    // system requested the user for permission during this call
    // only possible when force set to true
  }

  if (statusRequest.granted) {
    // the user did grant the permission now
    return true;
  }

  // user did not grant the permission, so he must have declined the request
  return false;
};

didUserGrantPermission();
```

如果用户拒绝给予良好许可, `status.denied` 将被设定为真实。 在Android上,这只有在用户检查盒子时才会发生 `never ask again`。无论如何,要获得许可,您必须将用户重定向到应用程序的设置上。 这样做可以简单地做到以下几点:

```js
import { BarcodeScanner } from '@capacitor-community/barcode-scanner';

const checkPermission = async () => {
  const status = await BarcodeScanner.checkPermission();

  if (status.denied) {
    // the user denied permission for good
    // redirect user to app settings if they want to grant it anyway
    const c = confirm('If you want to grant permission for using your camera, enable it in the app settings.');
    if (c) {
      BarcodeScanner.openAppSettings();
    }
  }
};
```

### 只针对特定条码

您可以设置扫描仪, 只识别特定类型的条码 :

```ts
import { BarcodeScanner, SupportedFormat } from '@capacitor-community/barcode-scanner';

BarcodeScanner.startScan({ targetedFormats: [SupportedFormat.QR_CODE] }); // this will now only target QR-codes
```

若为 `targetedFormats` 实值 _未指定_ 或者说 _留为空_, (中文(简体) ), _所有类型_ 条形码将被锁定.

仅针对特定类型可带来以下好处:

-   改进性能( 因为解码器只需查找指定的条码)
-   改进用户经验(因为扫描一个没有您大小写支持的条码,不会奏效)

支持下列类型:

| 类别 | 类型 | 机器人 | iOS系统 |
| --- | --- | --- | --- |
| 1D 产品 |
| 刚果爱国者联盟-A | ✔ | ✔\*\* |
| 刚果爱国者联盟 | ✔ | ✔ |
| 刚果爱国者联盟 延长 | ✔ | ✖ |
| 东风 8 | ✔ | ✔ |
| 东经 13 | ✔ | ✔ |
| 1D 工业 |
| CODE 39 (英语) | ✔ | ✔ |
| CODE 39 MOD 43 (英语) | ✖ | ✔ |
| CODE 93 (英语) | ✔ | ✔ |
| CODE 128 (英语) | ✔ | ✔ |
| 库巴 | ✔ | ✖ |
| 机构间工作组 | ✔ | ✔ |
| ITF 14 (中文(简体) ) | ✖ | ✔ |
| 二维 |
| 阿兹特 | ✔ | ✔ |
| 数据( MATRIX) | ✔ | ✔ |
| 马西科德 | ✔ | ✖ |
| PDF 417 (中文(简体) ) | ✔ | ✔ |
| QR CODE 代码 | ✔ | ✔ |
| RSS 14 软件 | ✔ | ✖ |
| 已执行 | ✔ | ✖ |

页:1 `UPC_A` 支持在 iOS 上,但根据函数 [苹果文档](https://developer.apple.com/documentation/avfoundation/avmetadataobject/objecttype/1618807-ean13) 它属于 `EAN_13`。所以您应当指定 `EAN_13` 可以扫描这个。 如果要将它们区分开来,应当在得到结果后手动进行.

## 解决问题

### Ionic CSS 变量

Ionic将增加额外的CSS变量,从而阻止扫描仪出现. 要解决这个问题, 在您的全球 cs 结尾处添加以下片段 .

```css
body.scanner-active {
  --background: transparent;
  --ion-background-color: transparent;
}
```

完成后,在使用扫描仪前,需要先将这一类加入到体内.

```typescript
document.querySelector('body').classList.add('scanner-active');
```

完成扫描工作后,可以简单地去掉这个课.

```typescript
document.querySelector('body').classList.remove('scanner-active');
```

### 我有一个 `Error: Plugin BarcodeScanner does not respond to method call` iOS 上的错误消息

在Xcode 点击 `Product` > 翻译: `Clean Build Folder` 并尝试再建设.

### 我有一个 `Cannot resolve symbol BarcodeScanner` android 工作室中的错误消息

在 Android 工作室点击 `File` > 翻译: `Sync Project with Gradle Files` 并尝试再建设.

### 扫描视图没有显示

如果您无法在取景口看到扫描仪,请遵循这些步骤:

1.  检查是否正确授予相机权限
2.  检查扫描仪元素是否出现在DOM内部,某处 `body` 标签
    -   [不在这](https://npmcn.com/package/%40capacitor-community/barcode-scanner/#readme-i-do-not-find-the-scanner-in-the-dom)
3.  检查扫描仪上是否有一些 DOM 元素
    -   搜索导致问题的元素 [7号](https://github.com/capacitor-community/barcode-scanner/issues/7#issuecomment-744441148)
    -   玩 Javascript [26号](https://github.com/capacitor-community/barcode-scanner/issues/26)

### 我找不到DOM的扫描仪

这应该在 DOM 运行时显示 `BarcodeScanner.startScan()` 方法.

```html
<body>
  <!-- ... -->
  <div style="position: absolute; left: 0px; top: -2px; height: 1px; overflow: hidden; visibility: hidden; width: 1px;">
    <span
      style="position: absolute; font-size: 300px; width: auto; height: auto; margin: 0px; padding: 0px; font-family: Roboto, Arial, sans-serif;"
      >BESbswy</span
    >
  </div>
  <!-- ... -->
</body>
```

如果不是,则可能由于组件被加载到DOM树深处而成为出错. 您可以尝试通过在您的插件中添加以下内容来查看插件是否正常工作 `app.component.ts` 文档.

```typescript
BarcodeScanner.hideBackground();
const result = await BarcodeScanner.startScan();
```

#### 它没有出现

可能意味着你错过了一步 [插件配置](https://npmcn.com/package/%40capacitor-community/barcode-scanner/#readme-installation)。 。 。 .

#### 我做了正确的配置

请 [打开一个问题](https://github.com/capacitor-community/barcode-scanner/issues/new/choose)

## 开始

非详尽的待办事宜列表:

-   相机间切换支持
-   网络支持

## 常见问题

### @capacitor-community/barcode-scanner 是什么？

快速而高效的Capacitor\(QR\)条码扫描仪

### 如何安装 @capacitor-community/barcode-scanner？

在项目目录运行 npm install @capacitor-community/barcode-scanner，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：@capacitor/core（^5\.0\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @capacitor-community/barcode-scanner 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @capacitor-community/barcode-scanner 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @capacitor-community/barcode-scanner 可以商用吗？

@capacitor-community/barcode-scanner 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @capacitor-community/barcode-scanner 的下载量有多少？

根据 npm 官方下载统计，@capacitor-community/barcode-scanner 在 2026/10/09 – 2026/11/07 这 30 天内被下载 51,088 次，日均约 1,703 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @capacitor-community/barcode-scanner 还在维护吗？

最新版本 4\.0\.1 发布于 2023/05/09（3 年前）；至今共发布 18 个版本，其中过去 12 个月发布了 0 个；首次发布于 2021/03/16。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

