npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@tencent-yb/sdk

v1.0.12

Published

元宝客户端 JS SDK — 对外版本

Readme

@tencent-yb/sdk 文档

概述

YB-JSSDK 是元宝客户端提供的 JavaScript SDK,用于在 WebView 中与原生应用进行交互。本文档介绍所有对外开放的公共 API 接口。

安装

npm install @tencent-yb/sdk

快速开始

使用任何 API 之前,先调用 config 方法完成鉴权:

import YuanbaoSDK from '@tencent-yb/sdk';

await YuanbaoSDK.config({
  appId: 'your_app_id',
  nonceStr: 'random_string',
  timestamp: 1700000000,
  signature: 'computed_signature',
});

⚠️ appSecret 仅可在服务端使用,严禁暴露到前端。签名计算规则为 hash(appId + nonceStr + timestamp + appSecret)。


API 分类

1. 核心配置

2. App 模块

3. Device 模块

4. UI 模块

5. WebView 模块

6. Share 模块


详细 API 文档

config

配置 SDK 并完成鉴权。所有需要使用 JS-SDK 的页面必须先调用此方法,否则将无法调用其他 API。

接口定义

function config(options: ConfigOptions): Promise<Response>

interface ConfigOptions {
  /** 开启调试模式,调用的所有 API 的返回值会在客户端 alert 出来 */
  debug?: boolean;
  /** 应用唯一标识(必填) */
  appId: string;
  /** 生成签名的时间戳(必填) */
  timestamp: number;
  /** 生成签名的随机串(必填) */
  nonceStr: string;
  /** 签名(必填) */
  signature: string;
  /** 需要使用的 JS 接口列表(必填) */
  jsApiList: string[];
}

interface Response {
  /** 状态码,0 表示成功,非 0 表示失败 */
  code: number;
  /** 错误信息 */
  errMsg: string;
  /** 返回数据 */
  data?: any;
}

示例

import YuanbaoSDK from '@tencent-yb/sdk';

try {
  const res = await YuanbaoSDK.config({
    appId: 'your_app_id',
    nonceStr: 'random_string',
    timestamp: 1700000000,
    signature: 'computed_signature',
  });
  console.log('鉴权成功:', res);
} catch (err) {
  console.error('鉴权失败:', err);
}

app.getTheme

获取当前 App 主题(深色/浅色模式),确保页面与元宝主题风格一致。

接口定义

interface GetThemeData {
  /** 是否深色模式:"0" 浅色,"1" 深色 */
  isDarkMode: string;
  /** 字体大小级别 */
  fontLevel: string;
  /** 底部 Tab 栏高度(px),0 表示无底部 Tab */
  bottomTabHeight: number;
}

function getTheme(): Promise<Response<GetThemeData>>

示例

import { app } from '@tencent-yb/sdk';

const res = await app.getTheme();
if (res.code === 0) {
  const isDark = res.data.isDarkMode === '1';
  console.log('深色模式:', isDark);
  console.log('字体级别:', res.data.fontLevel);
}

app.getServerTimestamp

获取服务端校准时间,用于订单超时倒计时、限时优惠等时效性逻辑。

接口定义

enum TimestampType {
  /** 毫秒级时间戳 */
  timestampMsec = 'timestampMsec',
  /** NTP 时间戳 */
  timestampNtp = 'timestampNtp',
}

interface GetServerTimestampParams {
  /** 时间戳类型 */
  type: TimestampType;
}

interface GetServerTimestampData {
  /** 服务端时间戳(毫秒) */
  timestampMsec?: number;
  /** NTP 时间戳 */
  timestampNtp?: number;
}

function getServerTimestamp(params: GetServerTimestampParams): Promise<Response<GetServerTimestampData>>

示例

import { app, TimestampType } from '@tencent-yb/sdk';

// 获取毫秒级时间戳
const res = await app.getServerTimestamp({ type: TimestampType.timestampMsec });
if (res.code === 0) {
  console.log('服务端时间戳:', res.data.timestampMsec);
}

app.setScreenCaptureEnabled

控制当前 WebView 是否允许截屏和录屏,用于支付密码等敏感页面的安全防护。

接口定义

interface SetScreenCaptureEnabledParams {
  /** 是否允许截屏录屏,false 禁止,true 允许 */
  enabled: boolean;
}

function setScreenCaptureEnabled(params: SetScreenCaptureEnabledParams): Promise<Response>

注意事项

  • 页面关闭(navigateBack)时客户端应自动恢复允许截屏录屏,防止影响后续页面。

示例

import { app } from '@tencent-yb/sdk';

// 进入支付密码页面时禁止截屏录屏
await app.setScreenCaptureEnabled({ enabled: false });

// 离开敏感页面后恢复
await app.setScreenCaptureEnabled({ enabled: true });

device.getLocation

获取当前地理位置,返回经纬度、速度和精度信息。用于外卖配送地址、附近商家推荐。

接口定义

type LocationType = 'wgs84' | 'gcj02';

interface GetLocationParams {
  /**
   * 坐标类型,默认为 'wgs84'
   * - wgs84: GPS 坐标
   * - gcj02: 国测局坐标(火星坐标)
   */
  type?: LocationType;
}

interface LocationData {
  /** 纬度,范围 -90 ~ 90 */
  latitude: number;
  /** 经度,范围 -180 ~ 180 */
  longitude: number;
  /** 速度,单位 m/s */
  speed?: number;
  /** 精度,单位 m */
  accuracy?: number;
}

function getLocation(params?: GetLocationParams): Promise<Response<LocationData>>

示例

import { device } from '@tencent-yb/sdk';

const res = await device.getLocation({ type: 'gcj02' });
if (res.code === 0 && res.data) {
  console.log('纬度:', res.data.latitude);
  console.log('经度:', res.data.longitude);
}

ui.toast

弹出原生 Toast 提示,如"添加购物车成功"、"下单成功"等操作反馈。

接口定义

interface ToastParams {
  /** 提示文本 */
  text: string;
}

function toast(params: ToastParams): Promise<Response>

示例

import { ui } from '@tencent-yb/sdk';

await ui.toast({ text: '添加购物车成功' });

webview.navigate

页面导航跳转:

  1. 传 url + ratio:打开 BottomSheetDialog 半屏/近全屏 WebView。
  2. 传 url 且不传 ratio:打开普通 WebView,支持 title 自定义导航栏标题。

接口定义

/** WebView 展示高度比例(占屏幕高度的十分之几) */
type NavigateWebViewRatio = 9 | 7;

/** navigate 请求参数 */
type NavigateParams = {
  /** 目标页面 URL */
  url: string;
  /** WebView 展示高度比例:不传默认全屏;9 表示 90% 屏幕高度(近全屏)、7 表示 70% 屏幕高度(半屏) */
  ratio?: NavigateWebViewRatio;
  /** 是否隐藏导航栏,默认 false */
  navigationBarHidden?: boolean;
  /** 导航栏标题(仅在未传 ratio 时生效) */
  title?: string;
  /** 跳转后是否关闭当前 webview */
  closeSelf?: boolean;
};

function navigate(params: NavigateParams): Promise<Response>

参数说明

| 参数 | 类型 | 必填 | 说明 | |------|------|------|------| | url | string | 条件 | 目标页面 URL,与 route 二选一 | | ratio | 9 | 7 | 否 | 9 表示 90% 近全屏,7 表示 70% 半屏;不传则走普通 WebView | | navigationBarHidden | boolean | 否 | 是否隐藏顶部导航栏;传 ratio 时映射为 navigationBarHidden,未传 ratio 时映射为 hideNavBar | | title | string | 否 | 导航栏标题,仅在未传 ratio(普通 WebView)时生效 | | closeSelf | boolean | 否 | 跳转后是否关闭当前 webview |

示例

import { webview } from '@tencent-yb/sdk';

// 1. 打开半屏 WebView(70% 高度)
await webview.navigate({
  url: 'https://yuanbao.com/shop/detail',
  ratio: 7,
});

// 2. 打开近全屏 WebView 并隐藏导航栏
await webview.navigate({
  url: 'https://yuanbao.com/order/confirm',
  ratio: 9,
  navigationBarHidden: true,
});

// 3. 打开普通 WebView(不传 ratio),自定义标题
await webview.navigate({
  url: 'https://qq.com',
  title: '1234',
});

webview.navigateBack

返回上一级页面(页面栈回退一层)。若当前 WebView 内存在多级页面历史,将回退到上一页;否则由客户端处理默认行为。

接口定义

function navigateBack(): Promise<Response>

示例

import { webview } from '@tencent-yb/sdk';

await webview.navigateBack();

webview.close

关闭当前 WebView(整个 WebView 容器直接退出),无论当前页面栈中是否还有历史页面。常用于完成任务后主动结束流程,例如支付完成、分享成功后关闭半屏/全屏 WebView。

与 navigateBack 的区别:

  • navigateBack:回退一页(页面栈 pop 一层),仍停留在 WebView 内。
  • close:关闭整个 WebView,直接退出当前容器。

接口定义

function close(): Promise<Response>

示例

import { webview } from '@tencent-yb/sdk';

try {
  const res = await webview.close();
  console.log('关闭成功:', res);
} catch (err) {
  console.error('关闭失败:', err);
}

webview.subscribe

【父 WebView 调用】监听子 WebView 发送的数据。通过 propertyId 区分不同业务方的信道。

接口定义

interface SubscribeParams {
  /** 信道标识,需与子 WebView broadcast 的 propertyId 一致 */
  propertyId: string;
}

interface WebviewDataPayload {
  /** 业务状态码,0 表示成功 */
  code: number;
  /** 错误描述信息 */
  errMsg: string;
  /** 业务数据 */
  data?: Record<string, unknown>;
}

function subscribe(
  params: SubscribeParams,
  callback: (payload: WebviewDataPayload) => void
): Promise<Response | null>

示例

import { webview } from '@tencent-yb/sdk';

// 父 WebView 注册监听
await webview.subscribe({ propertyId: 'yuanbao' }, (payload) => {
  if (payload.code === 0) {
    console.log('收到子 WebView 数据:', payload.data);
  }
});

// 然后打开子 WebView
await webview.navigate({
  url: 'https://yuanbao.com/order/confirm',
  ratio: 9,
  navigationBarHidden: true
});

webview.broadcast

【子 WebView 调用】向父 WebView 发送数据。

接口定义

interface BroadcastParams extends WebviewDataPayload {
  /** 信道标识,需与父 WebView subscribe 的 propertyId 一致 */
  propertyId: string;
}

interface Response<T = unknown> {
  /** 状态码,0 表示成功,非 0 表示失败 */
  code: ResponseCode | number;
  /** 错误信息 */
  errMsg: string | ErrMsg;
  /** 返回数据,操作成功时包含的额外数据 */
  data?: T;
}

function broadcast(params: BroadcastParams): Promise<Response>

示例

import { webview } from '@tencent-yb/sdk';

// 子 WebView 发送数据
const broadcastResult = await webview.broadcast({
  propertyId: 'yuanbao',
  code: 0,
  errMsg: 'ok',
  data: { orderStatus: 'success', orderId: '123456' }
});

// 发送后可选择关闭自身
await webview.navigateBack();

webview.onBackPressed

拦截用户的左滑手势和导航栏返回按钮行为。页面注册拦截后,用户触发返回时不会直接关闭 WebView,而是触发回调由页面自行处理(如回到收银台首页)。

接口定义

interface OnBackPressedParams {
  /** 是否启用返回拦截,true 启用,false 取消拦截恢复默认行为 */
  enabled: boolean;
}

function onBackPressed(
  params: OnBackPressedParams,
  callback?: () => void
): Promise<Response | null>

参数说明

| 参数 | 类型 | 必填 | 说明 | |------|------|------|------| | enabled | boolean | ✅ 是 | true 启用拦截(需同时传入 callback),false 取消拦截 | | callback | () => void | 否 | 拦截后的回调,enabled 为 true 时必传 |

示例

import { webview } from '@tencent-yb/sdk';

// 启用返回拦截 —— 收银台二级流程页
await webview.onBackPressed({ enabled: true }, () => {
  // 用户点击返回时,回到收银台首页而不是关闭 WebView
  router.push('/checkout');
});

// 取消返回拦截 —— 回到首页后恢复默认行为
await webview.onBackPressed({ enabled: false });

share.shareTo

支持将商家/商品/优惠信息分享给好友。

接口定义

type ShareToScene = 'session' | 'timeline' | 'qq' | 'qzone' | 'weibo';

enum ShareToType {
  webpage = 'webpage',
  image = 'image',
  video = 'video',
  file = 'file',
  text = 'text',
}

interface ShareToParams {
  /** 分享场景 */
  scene: ShareToScene;
  /** 分享类型 */
  type: ShareToType;
  /** 分享数据 */
  data: unknown;
}

function shareTo(params: ShareToParams): Promise<Response>

示例

import { share, ShareToType } from '@tencent-yb/sdk';

await share.shareTo({
  scene: 'session',
  type: ShareToType.webpage,
  data: {
    url: 'https://yuanbao.com/shop/12345',
    title: '摇滚霸王',
    description: '一起来摇滚吧!',
    thumbUrl: 'https://example.com/shop-logo.jpg'
  }
});

持久化存储

数据持久化直接使用浏览器原生 localStorage,无需通过 Bridge。

// 写入数据(建议添加业务前缀避免冲突)
localStorage.setItem('yuanbao_cart_data', JSON.stringify({ items: [...] }));

// 读取数据
const cartData = JSON.parse(localStorage.getItem('yuanbao_cart_data') ?? 'null');

完整业务流程示例

import { config, app, device, webview, ui, share, TimestampType } from '@tencent-yb/sdk';

// 1. 鉴权
await config({
  appId: 'your_app_id',
  nonceStr: 'random_string',
  timestamp: 1700000000,
  signature: 'computed_signature',
  jsApiList: [
    'getTheme', 'getServerTimestamp', 'getLocation',
    'toast', 'navigate', 'navigateBack',
    'subscribe', 'broadcast', 'onBackPressed',
    'setScreenCaptureEnabled', 'shareTo'
  ]
});

// 2. 获取主题适配 UI
const themeRes = await app.getTheme();
const isDark = themeRes.data.theme === 'dark';

// 3. 获取位置推荐附近商家
const locRes = await device.getLocation({ type: 'gcj02' });

// 4. 父 WebView 注册数据监听
await webview.subscribe({ propertyId: 'yuanbao' }, (payload) => {
  if (payload.code === 0 && payload.data?.orderStatus === 'success') {
    ui.toast({ text: '下单成功!' });
  }
});

// 5. 打开订单确认页(近全屏 BottomSheetDialog)
await webview.navigate({
  url: 'https://yuanbao.com/order/confirm',
  ratio: 9,
  navigationBarHidden: true
});

// 6. 子 WebView 中:启用返回拦截
await webview.onBackPressed({ enabled: true }, () => {
  router.push('/checkout');
});

// 7. 子 WebView 中:进入支付页面前禁止截屏
await app.setScreenCaptureEnabled({ enabled: false });

// 8. 子 WebView 中:支付完成后发送数据并返回
await webview.broadcast({
  propertyId: 'yuanbao',
  code: 0,
  errMsg: 'ok',
  data: { orderStatus: 'success', orderId: '123456', totalAmount: 29.9 }
});
await webview.navigateBack();

类型定义

完整的 TypeScript 类型定义请参考 SDK 包中的类型声明文件。


版本说明

当前文档基于 YB-JSSDK v1.0.0 版本编写。

技术支持

如有问题,请联系技术支持团队。