@googleworkspace/drive-picker-element

中文文档
0.7.3发布于 2025/12/10Apache-2.0TypeScriptES Module零依赖构建来源已验证近 30 天下载 82.3万

A web component for Google Drive Picker

原始使用文档
文档目录16 节
  1. Description
  2. Index
  3. Install
  4. Usage
  5. Import the Component
  6. Add the Component to Your HTML
  7. Use the oauth-token attribute
  8. Listening to Events
  9. Event Details
  10. Controlling Visibility
  11. React
  12. Content Security Policy (CSP)
  13. Support
  14. Reference
  15. <drive-picker/>
  16. <drive-picker-docs-view/>

npm Test Release

Description

The Google Drive Picker web component offers a seamless way to integrate the Google Picker API into your web applications. This component is framework-agnostic, meaning it works effortlessly with React, Svelte, Vue, Angular, and more.

The Google Picker API is a JavaScript API that allows users to select or upload Google Drive files. This component acts as a "File Open" dialog, providing access to and interaction with files stored on Google Drive.

Explore the storybook demo to see the component in action.

See the framework specific components:

Index

Install

Install using NPM or similar.

npm i @googleworkspace/drive-picker-element

A CDN version is also available. See the unpkg.

<script src="https://unpkg.com/@googleworkspace/drive-picker-element/dist/index.iife.min.js"></script>

Usage

To use the drive-picker component in your project, follow these steps:

Import the Component

First, import the drive-picker component in your JavaScript file:

import "@googleworkspace/drive-picker-element";

This isn't necessary if you're using the CDN version.

Add the Component to Your HTML

Next, add the drive-picker component to your HTML file. Replace YOUR_CLIENT_ID and YOUR_APP_ID with your actual client ID and app ID.

Note: You can find these values in the Google Cloud Console under "APIs & Services" > "Credentials". You can also follow this guide to create a new OAuth 2.0 client ID.

<drive-picker client-id="YOUR_CLIENT_ID" app-id="YOUR_APP_ID">
  <drive-picker-docs-view starred="true"></drive-picker-docs-view>
</drive-picker>

Note: If you wish to register the component with a different name, you can import the components individually and call customElements.define() manually:

import {
  DrivePickerElement,
  DrivePickerDocsViewElement,
} from "@googleworkspace/drive-picker-element/drive-picker";
customElements.define("custom-drive-picker", DrivePickerElement);
customElements.define(
  "custom-drive-picker-docs-view",
  DrivePickerDocsViewElement,
);

Use the oauth-token attribute

If you already have an OAuth token, you can pass it to the drive-picker component using the oauth-token attribute. This will authenticate the user without requiring them to sign in again.

<drive-picker app-id="YOUR_APP_ID" oauth-token="OAUTH_TOKEN"></drive-picker>

If you don't have an OAuth token, you can listen for the "picker-oauth-response" event to get the token after the user has authenticated. This library wraps the Google Identity Services library to make it easier to authenticate users.

Listening to Events

The drive-picker component emits several events that you can listen to. Here is an example of how to listen to these events:

<drive-picker client-id="YOUR_CLIENT_ID" app-id="YOUR_APP_ID">
  <drive-picker-docs-view starred="true"></drive-picker-docs-view>
</drive-picker>

<script>
  const element = document.querySelector("drive-picker");
  element.addEventListener("picker-oauth-response", console.log);
  element.addEventListener("picker-oauth-error", console.log);
  element.addEventListener("picker-picked", console.log);
  element.addEventListener("picker-canceled", console.log);
</script>

Event Details

Most of these events return the Picker ResponseObject as the event detail. For example, the "picker-picked" CustomEvent contains details about the selected files:

{
  "type": "picker-picked",
  "detail": {
    "action": "picked",
    "docs": [
      {
        "id": "OMITTED",
        "mimeType": "application/pdf",
        "name": "OMITTED",
        "url": "https://drive.google.com/file/d/OMITTED/view?usp=drive_web",
        "sizeBytes": 12345
        // ... other properties omitted
      }
    ]
  }
}

The "picker-oauth-response" event returns the OAuth token response as the event detail:

{
  "type": "picker-oauth-response",
  "detail": {
    "access_token": "OMITTED",
    "expires_in": 3599,
    "scope": "https://www.googleapis.com/auth/drive.file",
    "token_type": "Bearer"
  }
}

Controlling Visibility

To make the picker visible, set the visible property of the drive-picker element to true:

<drive-picker client-id="YOUR_CLIENT_ID" app-id="YOUR_APP_ID"></drive-picker>

<script>
  const element = document.querySelector("drive-picker");
  element.visible = true;
</script>

After the picker dialog has been closed, the visible property will be reset to false.

React

For React applications, we recommend using the official React wrapper package: @googleworkspace/drive-picker-react.

Please refer to the package documentation for usage instructions.

Content Security Policy (CSP)

This library dynamically loads the Google API scripts (https://apis.google.com/js/api.js and https://accounts.google.com/gsi/client) if they are not already present. This may violate strict CSP settings that disallow dynamic script injection or restrict script sources.

To use this library in a strict CSP environment:

  1. Pre-load the scripts: Manually include the Google API scripts in your HTML using <script> tags that comply with your CSP (e.g., using a nonce or allowing the domain).

    <script src="https://apis.google.com/js/api.js" async defer></script>
    <script src="https://accounts.google.com/gsi/client" async defer></script>
    
  2. Ensure global objects are available: The library checks for window.gapi and window.google.accounts.oauth2. If these are present, it skips the dynamic injection.

  3. Allow Google domains in CSP: You must allow the picker's origin and other Google domains in your Content-Security-Policy. Here is a complete example:

    Content-Security-Policy:
      default-src 'self';
      script-src 'self' https://apis.google.com https://accounts.google.com;
      frame-src 'self' https://docs.google.com https://drive.google.com https://accounts.google.com;
      style-src 'self' 'unsafe-inline';
      img-src 'self' https://*.googleusercontent.com;
      connect-src 'self' https://*.googleapis.com;
      font-src 'self' https://fonts.gstatic.com;
    

    Notes:

    • The frame-src domains are required for the Picker iframe and authentication. The exact domains may vary, but these are the most common.
    • style-src: 'unsafe-inline' may be required for some styles injected by the Picker. For a stricter policy, you can use nonces.

Note for Chrome Extensions (Manifest V3): The underlying Google Picker API relies on gapi, which is not supported in Manifest V3 extensions. Therefore, this library may not function in that environment regardless of CSP settings.

Support

To report issues or feature requests for the underlying Drive Picker, please use the Google Picker issue tracker. For all other issues, please use the GitHub issue tracker.

Reference

<drive-picker/>

The drive-picker web component provides a convenient way to declaratively build google.picker.Picker by using the component attributes mapped to the corresponding methods of google.picker.PickerBuilder.

Attributes

NameTypeDescription
app-idstringThe Google Drive app ID. See PickerBuilder.setAppId.
client-idstringThe OAuth 2.0 client ID. See Using OAuth 2.0 to Access Google APIs.
debounce-delaynumberThe debounce delay in milliseconds before building the picker after an attribute change.
developer-keystringThe API key for accessing Google Picker API. See PickerBuilder.setDeveloperKey.
hide-title-bar"default"|"true"|"false"Hides the title bar of the picker if set to true. See PickerBuilder.hideTitleBar.
localestringThe locale to use for the picker. See PickerBuilder.setLocale.
max-itemsnumberThe maximum number of items that can be selected. See PickerBuilder.setMaxItems.
mine-onlybooleanIf set to true, only shows files owned by the user. See PickerBuilder.enableFeature.
multiselectbooleanEnables multiple file selection if set to true. See PickerBuilder.enableFeature.
nav-hiddenbooleanHides the navigation pane if set to true. See PickerBuilder.enableFeature.
oauth-tokenstringThe OAuth 2.0 token for authentication. See PickerBuilder.setOAuthToken.
originstringThe origin parameter for the picker. See PickerBuilder.setOrigin.
relay-urlstringThe relay URL for the picker. See PickerBuilder.setRelayUrl.
scopestringThe OAuth 2.0 scope for the picker. The default is https://www.googleapis.com/auth/drive.file. See Drive API scopes.
titlestringThe title of the picker. See PickerBuilder.setTitle.
hdstringThe hosted domain to restrict sign-in to. (Optional) See the hd field in the OpenID Connect docs.
include-granted-scopesbooleanEnables applications to use incremental authorization. See TokenClientConfig.include_granted_scopes.
login-hintstringAn email address or an ID token 'sub' value. Google will use the value as a hint of which user to sign in. See the login_hint field in the OpenID Connect docs.
prompt""|"none"|"consent"|"select_account"A space-delimited, case-sensitive list of prompts to present the user. See TokenClientConfig.prompt

Events

NameTypeDescription
picker-oauth-errorOAuthErrorEventTriggered when an error occurs in the OAuth flow. See the error guide. Note that the TokenResponse object can have error fields.
picker-oauth-responseOAuthResponseEventTriggered when an OAuth flow completes. See the token model guide.
picker-canceledPickerCanceledEventTriggered when the user cancels the picker dialog. See ResponseObject.
picker-pickedPickerPickedEventTriggered when the user picks one or more items. See ResponseObject.
picker-errorPickerErrorEventTriggered when an error occurs. See ResponseObject.

Slots

NameDescription
defaultThe default slot contains View elements to display in the picker. Each View element should implement a property view of type google.picker.View.

Properties

NameTypeDescription
visiblebooleanControls the visibility of the picker after the picker dialog has been closed. If any of the attributes change, the picker will be rebuilt and the visibility will be reset.
tokenClientConfig`Omit<
    google.accounts.oauth2.TokenClientConfig,
    "callback" \| "error_callback" 	>` |                                                                                                                                                                                      |

<drive-picker-docs-view/>

The drive-picker-docs-view element is used to define a google.picker.DocsView.

Attributes

NameTypeDescription
enable-drives"default"|"true"|"false"Whether to allow the user to select files from shared drives. See DocsView.enableDrives.
file-idsstringA comma-separated list of file IDs to filter the view. See View.setFileIds.
include-folders"default"|"true"|"false"Whether to include folders in the view. See DocsView.includeFolders.
mime-typesstringA comma-separated list of MIME types to filter the view. See View.setMimeTypes.
modestringThe mode of the view. See DocsViewMode.
owned-by-me"default"|"true"|"false"Whether to show files owned by the user. See DocsView.ownedByMe.
parentstringThe ID of the folder to view. See DocsView.setParent.
querystringThe query string to filter the view. See View.setQuery.
select-folder-enabled"default"|"true"|"false"Whether to allow the user to select folders. See DocsView.selectFolderEnabled.
starred"default"|"true"|"false"Whether to show starred files. See DocsView.starred.
view-idstringThe keyof typeof google.picker.ViewId. For example, "DOCS", which is equivalent to google.picker.ViewId.DOCS. See ViewId.

Properties

NameTypeDescription
viewgoogle.picker.DocsViewGets the Google Drive Picker view based on the current attribute values.

版本与发布记录

@googleworkspace/drive-picker-element 共发布 27 个版本,首次发布于 2024/08/20;过去 12 个月发布了 6 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.7.3latest2025/12/1011 个月前
0.7.22025/12/0511 个月前
0.7.12025/12/0211 个月前
0.7.02025/11/2011 个月前
0.6.52025/11/1911 个月前
0.6.42025/11/1911 个月前

关于 @googleworkspace/drive-picker-element 的常见问题

@googleworkspace/drive-picker-element 是什么?

A web component for Google Drive Picker

如何安装 @googleworkspace/drive-picker-element?

在项目目录运行 npm install @googleworkspace/drive-picker-element,或使用 pnpm add / yarn add / bun add。

@googleworkspace/drive-picker-element 支持 TypeScript 吗?

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

@googleworkspace/drive-picker-element 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@googleworkspace/drive-picker-element 可以商用吗?

@googleworkspace/drive-picker-element 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@googleworkspace/drive-picker-element 的下载量有多少?

根据 npm 官方下载统计,@googleworkspace/drive-picker-element 在 2026/10/17 – 2026/11/15 这 30 天内被下载 822,737 次,日均约 27,425 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@googleworkspace/drive-picker-element 还在维护吗?

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