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

lt-iframe-sdk

v1.1.0

Published

LT Agent iframe communication SDK

Downloads

52

Readme

lt-iframe-sdk

用于父页面与 iframe 之间双向通信的 SDK,基于 postMessage 协议。

安装

npm install lt-iframe-sdk

快速开始

import { createSdkInstance } from 'lt-iframe-sdk';

const sdk = createSdkInstance({
  sdkName: 'LtDemo-Sdk',
  iframeElement: document.getElementById('my-iframe') as HTMLIFrameElement,
  iframeSrc: 'https://example.com/agent',
});

// 监听事件
sdk.on('PAGE_PREPARED', () => {
  sdk.startLoad();
});

sdk.on('INIT_FINISH', () => {
  console.log('初始化完成');
});

// 组件销毁时调用
sdk.destroy();

API

createSdkInstance(option)

创建 SDK 实例,返回 LtIframeSdk 对象。

option 参数

| 参数 | 类型 | 必填 | 默认值 | 说明 | | --- | --- | --- | --- | --- | | sdkName | string | 是 | - | 通信频道名称,父页面与 iframe 必须一致 | | iframeElement | HTMLIFrameElement | 否 | - | 要绑定的 iframe 元素,传入后无需再调用 bindIframe | | iframeSrc | string | 否 | - | iframe 页面地址,会在 bindIframe 执行时赋值给 iframe 元素 | | origin | string | 否 | '*' | 允许通信的源,建议生产环境设置为具体域名 | | useCustomRequestConfig | boolean | 否 | false | 是否自定义请求配置,设为 truegetRequestConfig 必传 | | getRequestConfig | () => Promise<RequestConfigResponse> | 条件必填 | - | 返回 iframe 内发起请求所需的配置(域名、token 等) | | useCustomUploadFile | boolean | 否 | false | 是否自定义文件上传,设为 trueuploadFile 必传 | | uploadFile | (params: UploadFilePayload) => Promise<string> | 条件必填 | - | 实现文件上传逻辑,返回上传后的资源 URL |

自定义请求配置示例

const sdk = createSdkInstance({
  sdkName: 'LtDemo-Sdk',
  useCustomRequestConfig: true,
  getRequestConfig: async () => ({
    domain: 'https://api.example.com/gateway',
    token: `Bearer ${yourToken}`,
    params: {},
  }),
});

自定义文件上传示例

const sdk = createSdkInstance({
  sdkName: 'LtDemo-Sdk',
  useCustomUploadFile: true,
  uploadFile: async ({ file }) => {
    const formData = new FormData();
    formData.append('file', file);
    const res = await fetch('/api/upload', { method: 'POST', body: formData });
    const data = await res.json();
    return data.url;
  },
});

同时启用两者

const sdk = createSdkInstance({
  sdkName: 'LtDemo-Sdk',
  useCustomRequestConfig: true,
  getRequestConfig: async () => ({
    domain: 'https://api.example.com/gateway',
    token: `Bearer ${yourToken}`,
  }),
  useCustomUploadFile: true,
  uploadFile: async ({ file }) => {
    // 上传逻辑...
    return 'https://cdn.example.com/file.png';
  },
});

实例方法

bindIframe(iframeElement: HTMLIFrameElement, iframeSrc?: string)

绑定 iframe 元素,并在绑定后将 iframeSrc 赋值给 iframe 元素。如果创建实例时已通过 iframeElement 参数传入,则无需再调用此方法。SDK 内部有消息缓冲机制,即使 iframe 在绑定前已发送消息(如 PAGE_PREPARED),也不会丢失,会在绑定后自动重放。

sdk.bindIframe(iframeRef.value, 'https://example.com/agent');

startLoad(params?: StartLoadParams)

通知 iframe 开始加载,通常在收到 PAGE_PREPARED 事件后调用。

sdk.startLoad({ botId: '123' });

createNewConversation()

通知 iframe 创建新会话。需在 INIT_FINISH 事件后调用。

sdk.createNewConversation();

on(event, handler) / off(event, handler)

监听 / 移除事件。

const handler = (data) => console.log(data);
sdk.on('INIT_FINISH', handler);
sdk.off('INIT_FINISH', handler);

registPromiseEvent(key, handler) / unRegistPromiseEvent(key)

注册 / 移除自定义的 Promise 事件处理器。当 iframe 发送 Promise 类型消息时,SDK 会查找对应 key 的处理器并将返回值回传给 iframe。

sdk.registPromiseEvent('GET_USER_INFO', async () => {
  return { name: '张三', role: 'admin' };
});

sdk.unRegistPromiseEvent('GET_USER_INFO');

promisePostMessage(key, value, options?)

向 iframe 发送 Promise 消息并等待回复。

const result = await sdk.promisePostMessage('FETCH_DATA', { id: 1 }, { timeout: 5000 });

sendMessage(key, value)

向 iframe 发送普通消息(无需回复)。

sdk.sendMessage('UPDATE_THEME', { mode: 'dark' });

destroy()

销毁 SDK 实例,一次性移除所有事件监听和 window.message 监听。组件卸载时调用即可,无需手动逐个 off

sdk.destroy();

内置事件

| 事件名 | 方向 | 说明 | | --- | --- | --- | | PAGE_PREPARED | iframe -> 父页面 | iframe 页面加载完成,SDK 自动回复 INIT_CONFIG | | INIT_FINISH | iframe -> 父页面 | iframe 内智能体初始化完成 | | NEW_TASK_CREATED | iframe -> 父页面 | 新会话创建成功 | | REQUEST_ERROR | iframe -> 父页面 | iframe 内请求出错 |

Vue 3 完整示例

<template>
  <iframe ref="iframeRef" />
</template>

<script setup lang="ts">
  import { onBeforeUnmount, onMounted, ref } from 'vue';
  import { createSdkInstance } from 'lt-iframe-sdk';
  import type { LtIframeSdk } from 'lt-iframe-sdk';

  const iframeRef = ref<HTMLIFrameElement>();
  const iframeSrc = 'https://example.com/agent';
  let sdk: LtIframeSdk;

  function onPagePrepared() {
    sdk.startLoad();
  }

  function onInitFinish() {
    console.log('智能体初始化完成');
  }

  onMounted(() => {
    sdk = createSdkInstance({
      sdkName: 'LtDemo-Sdk',
      iframeElement: iframeRef.value!,
      iframeSrc,
      useCustomRequestConfig: true,
      getRequestConfig: async () => ({
        domain: 'https://api.example.com/gateway',
        token: 'Bearer xxx',
      }),
    });

    sdk.on('PAGE_PREPARED', onPagePrepared);
    sdk.on('INIT_FINISH', onInitFinish);
  });

  onBeforeUnmount(() => {
    sdk.destroy();
  });
</script>

构建

cd lt-iframe-sdk
npm install
npm run build

构建产物输出到 dist/ 目录,包含 CJS、ESM 和类型声明文件。

类型导出

import type {
  SdkCreateOption,
  RequestConfigResponse,
  UploadFilePayload,
  StartLoadParams,
  RequestErrorPayload,
} from 'lt-iframe-sdk';