# ifapi

> iframe api

Latest version **3.0.2** (published 2024-07-26) · MIT license · 0 weekly downloads

## Install

```sh
npm install ifapi
pnpm add ifapi
yarn add ifapi
bun add ifapi
```

## Health

**Score 25/100 (F)** — status: abandoned.

Positive: has types; esm support; no vulnerabilities.

Warnings: low downloads.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 3.0.2 |
| Published | 2024-07-26 |
| First published | 2023-06-25 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 0 |
| Unpacked size | 15.3 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 0 |
| Author | zyc |
| Maintainers | zhou_yucheng |
| Keywords | iframe, api |

## Links

- npm: https://www.npmjs.com/package/ifapi
- Repository: https://github.com/ASpurple/ifapi
- Homepage: https://github.com/ASpurple/ifapi#readme
- Issues: https://github.com/ASpurple/ifapi/issues
- npm.io page: https://npm.io/package/ifapi

## Recent versions

- 3.0.2 (latest) — 2024-07-26
- 3.0.0 — 2024-07-25
- 2.0.2 — 2024-07-11
- 2.0.1 — 2024-07-11
- 2.0.0 — 2024-07-10
- 1.2.3 — 2023-08-24
- 1.2.2 — 2023-06-29
- 1.1.9 — 2023-06-29
- 1.1.8 — 2023-06-29
- 1.1.6 — 2023-06-25
- 1.1.5 — 2023-06-25
- 1.1.0 — 2023-06-25
- 1.0.6 — 2023-06-25
- 1.0.5 — 2023-06-25
- 1.0.2 — 2023-06-25
- … 2 more at https://npm.io/package/ifapi/versions

## README

## 说明

iframe 内嵌页面通过使用 window.postMessage 通信来导出一些函数供父级页面调用，从而避开跨域限制，在父页面调用导出的函数可直接获取到函数返回值。

## 使用方式

### 1. 安装

```sh
npm install ifapi --save
```

### 2. 使用

#### 1. iframe 内嵌页面导出 api

```ts
import { expose } from 'ifapi';

const handlers = {
    greet: function(name: string) {
        alert(`hello, ${name}`);
    },
    sum: function(a: number, b: number) {
        return a + b;
    }
}

expose(handlers);
```

#### 2. 父级页面调用 api
```ts
import { excute } from 'ifapi';

// <iframe id="my-frame" src="http://www.test.com/iframe.html"></iframe>

excute("my-frame", "greet");

excute("my-frame", "sum", 1, 2)
	.then((data) => console.log(data))
	.catch((error) => console.error(error));
```

#### 3. 导出的 api 被调用时校验 origin

```ts
import { expose } from 'ifapi';

function vertify(origin: string) {
    return origin == "www.xxxx.com";
}

expose(handlers, vertify);
```

#### 4. 取消导出

```ts
import { expose } from 'ifapi';

const unExpose = expose(handlers);

unExpose(); // 取消导出
```

---
_Source: https://npm.io/package/ifapi · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
