@capgo/capacitor-share-target

中文文档
8.0.65发布于 2026/11/02MPL-2.0TypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 11.8万

Receive shared content from other apps

原始使用文档
文档目录16 节
  1. ➡️ Get started for free
  2. Key features
  3. Compatibility
  4. Install
  5. Configuration
  6. Android
  7. iOS
  8. Usage
  9. API
  10. addListener('shareReceived', ...)
  11. removeAllListeners()
  12. getPluginVersion()
  13. Interfaces
  14. Example
  15. Contributing
  16. License

@capgo/capacitor-share-target

Let users share text, links, images and files from other apps straight into your Capacitor app, through the system share sheet on iOS and Android.

Capgo - Build Capacitor apps with AI, ship updates instantly

Capgo: push fixes to your Capacitor users in minutes, build signed iOS and Android apps without a Mac, and roll back in one click.

➡️ Get started for free

14-day unlimited free trial. No credit card required

🤖 Building with an AI coding agent? Install Capgo skills so Claude Code, Codex, Cursor, Copilot, or Gemini CLI know how to install and use @capgo/capacitor-share-target in your Capacitor app: npx skills add Cap-go/capgo-skills. Then ask your agent: "Add @capgo/capacitor-share-target to my Capacitor app and wire it up." Agent setup guides · Hosted MCP

@capgo/capacitor-share-target for Capacitor apps

Key features

  • Share event: the shareReceived listener delivers the title, texts and files.
  • Files: each shared file comes with its URI, name and MIME type. On iOS, your Share Extension must save these attachment details to the App Group.
  • Android: receives content through intent filters you set for the MIME types you want.
  • iOS: reads content saved by your Share Extension through an App Group set as appGroupId.
  • Platforms: iOS and Android. iOS needs a Share Extension target. Not available on web.

Compatibility

Plugin versionCapacitor compatibilityMaintained
v8.*.*v8.*.*✅
v7.*.*v7.*.*On demand
v6.*.*v6.*.*❌
v5.*.*v5.*.*❌

Note: The major version of this plugin follows the major version of Capacitor. Use the version that matches your Capacitor installation (e.g., plugin v8 for Capacitor 8). Only the latest major version is actively maintained.

Install

You can use our AI-Assisted Setup to install the plugin. Add the Capgo skills to your AI tool using the following command:

npx skills add https://github.com/cap-go/capacitor-skills --skill capacitor-plugins

Then use the following prompt:

Use the `capacitor-plugins` skill from `cap-go/capacitor-skills` to install the `@capgo/capacitor-share-target` plugin in my project.

If you prefer Manual Setup, install the plugin by running the following commands and follow the platform-specific instructions below:

npm install @capgo/capacitor-share-target
npx cap sync

Configuration

Android

Add the following to your AndroidManifest.xml inside the <activity> tag to allow your app to receive shared content:

<intent-filter>
    <action android:name="android.intent.action.SEND" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="text/*" />
</intent-filter>
<intent-filter>
    <action android:name="android.intent.action.SEND" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="image/*" />
</intent-filter>
<intent-filter>
    <action android:name="android.intent.action.SEND_MULTIPLE" />
    <category android:name="android.intent.category.DEFAULT" />
    <data android:mimeType="image/*" />
</intent-filter>

You can customize the mimeType to match the types of content you want to receive (e.g., text/*, image/*, video/*, */*).

iOS

For iOS, you need to create a Share Extension to receive shared content. This requires additional setup:

  1. In Xcode, go to File > New > Target
  2. Select "Share Extension" and click Next
  3. Name it (e.g., "ShareExtension") and click Finish
  4. Configure the Share Extension to save data to a shared App Group (e.g., group.com.yourcompany.app)
  5. Configure the plugin in your capacitor.config.ts or capacitor.config.json:
{
  plugins: {
    CapacitorShareTarget: {
      appGroupId: "group.com.yourcompany.app"
    }
  }
}
  1. In your ShareViewController.swift, save the shared data using the key "share-target-data" or "SharedData" to UserDefaults with your app group ID

Example ShareViewController.swift:

import UIKit
import UniformTypeIdentifiers

class ShareViewController: UIViewController {
    let APP_GROUP_ID = "group.com.yourcompany.app"  // Same as in capacitor.config
    let APP_URL_SCHEME = "yourapp"  // Your app's URL scheme
    
    private var texts: [[String: Any]] = []
    private var files: [[String: Any]] = []

    override public func viewDidLoad() {
        super.viewDidLoad()
        
        guard let extensionItem = extensionContext?.inputItems.first as? NSExtensionItem,
              let attachments = extensionItem.attachments else {
            self.exit()
            return
        }

        Task {
            // Process attachments...
            // (See full implementation in issue examples)
            
            // Save to UserDefaults
            let shareData: [String: Any] = [
                "title": extensionItem.attributedTitle?.string ?? "",
                "texts": texts,
                "files": files
            ]
            
            let userDefaults = UserDefaults(suiteName: APP_GROUP_ID)
            userDefaults?.set(shareData, forKey: "share-target-data")
            userDefaults?.synchronize()
            
            // Open main app with your URL scheme
            let url = URL(string: "\(APP_URL_SCHEME)://share")!
            self.openURL(url)
        }
    }
    
    // ... rest of implementation
}

For detailed instructions, see the iOS Share Extension documentation.

Usage

import { CapacitorShareTarget } from '@capgo/capacitor-share-target';

// Listen for shared content
CapacitorShareTarget.addListener('shareReceived', (event) => {
  console.log('Title:', event.title);
  console.log('Texts:', event.texts);

  event.files?.forEach(file => {
    console.log(`File: ${file.name}`);
    console.log(`Type: ${file.mimeType}`);
    console.log(`URI: ${file.uri}`);
  });
});

API

Capacitor Share Target Plugin interface.

This plugin allows your application to receive content shared from other apps. Users can share text, URLs, and files to your app from other applications.

addListener('shareReceived', ...)

addListener(eventName: 'shareReceived', listenerFunc: (event: ShareReceivedEvent) => void) => Promise<PluginListenerHandle>

Listen for shareReceived event.

Registers a listener that will be called when content is shared to the application from another app. The callback receives event data containing title, texts, and files.

ParamTypeDescription
eventName'shareReceived'The event name. Must be 'shareReceived'.
listenerFunc(event: ShareReceivedEvent) => voidCallback function invoked when content is shared to the app.

Returns: Promise<PluginListenerHandle>

Since: 0.1.0


removeAllListeners()

removeAllListeners() => Promise<void>

Remove all listeners for this plugin.

Since: 0.1.0


getPluginVersion()

getPluginVersion() => Promise<{ version: string; }>

Get the native Capacitor plugin version.

Returns the current version of the native plugin implementation.

Returns: Promise<{ version: string; }>

Since: 0.1.0


Interfaces

PluginListenerHandle

PropType
remove() => Promise<void>

ShareReceivedEvent

Event data received when content is shared to the application.

PropTypeDescriptionSince
titlestringThe title of the shared content.0.1.0
textsstring[]Array of text content shared to the application.0.1.0
filesSharedFile[]Array of files shared to the application.0.2.0

SharedFile

Represents a file shared to the application.

PropTypeDescriptionSince
uristringThe URI of the shared file. On Android/iOS this will be a file path or data URL. On web this will be a cached URL accessible via fetch.0.1.0
namestringThe name of the shared file, with or without extension.0.1.0
mimeTypestringThe MIME type of the shared file.0.1.0

Example

On Android, successful copies live under the app cache directory shared_files. The plugin removes copies older than 24 hours and caps how many are kept. When files[].uri is a path under that directory, delete it after you finish processing so large shares do not fill storage. If copying fails, files[].uri may be the original content URI instead.

Here's a complete example of handling shared content in your app:

import { CapacitorShareTarget } from '@capgo/capacitor-share-target';
import { Capacitor } from '@capacitor/core';

export class ShareService {
  async initialize() {
    // Only add listener on native platforms
    if (Capacitor.isNativePlatform()) {
      await CapacitorShareTarget.addListener('shareReceived', this.handleSharedContent);
    }
  }

  private handleSharedContent(event: ShareReceivedEvent) {
    console.log('Received shared content!');

    // Handle shared text
    if (event.texts.length > 0) {
      console.log('Shared text:', event.texts[0]);
      // Process the shared text (e.g., URL, note, etc.)
    }

    // Handle shared files
    if (event.files.length > 0) {
      event.files.forEach(async (file) => {
        console.log(`Processing file: ${file.name}`);

        if (file.mimeType.startsWith('image/')) {
          // Handle image files
          await this.processImage(file.uri);
        } else if (file.mimeType.startsWith('video/')) {
          // Handle video files
          await this.processVideo(file.uri);
        }
      });
    }
  }

  private async processImage(uri: string) {
    // Your image processing logic here
  }

  private async processVideo(uri: string) {
    // Your video processing logic here
  }

  async cleanup() {
    await CapacitorShareTarget.removeAllListeners();
  }
}

Contributing

See CONTRIBUTING.md.

License

MIT

版本与发布记录

@capgo/capacitor-share-target 共发布 71 个版本,首次发布于 2025/10/27;过去 12 个月发布了 67 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
8.0.65latest2026/11/026 天前
8.0.642026/10/2613 天前
8.0.632026/10/1920 天前
8.0.622026/10/1525 天前
8.0.612026/10/1327 天前
8.0.602026/10/1228 天前

关于 @capgo/capacitor-share-target 的常见问题

@capgo/capacitor-share-target 是什么?

Receive shared content from other apps

如何安装 @capgo/capacitor-share-target?

在项目目录运行 npm install @capgo/capacitor-share-target,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@capacitor/core(>=8.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@capgo/capacitor-share-target 支持 TypeScript 吗?

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

@capgo/capacitor-share-target 支持 ESM 还是 CommonJS?

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

@capgo/capacitor-share-target 可以商用吗?

@capgo/capacitor-share-target 使用 MPL-2.0 许可。弱 Copyleft:可以商用,也可以和闭源代码一起使用;但如果分发时修改了 MPL 授权的文件,这些文件的修改需以 MPL 开源。以上为概括,不构成法律意见,请以许可原文为准。

@capgo/capacitor-share-target 的下载量有多少?

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

@capgo/capacitor-share-target 还在维护吗?

最新版本 8.0.65 发布于 2026/11/02(6 天前);至今共发布 71 个版本,其中过去 12 个月发布了 67 个;首次发布于 2025/10/27。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。