# nw-mwa

> 多WebView页面共存App通信SDK(`nw-multi-webview-app-communication`)

Latest version **0.3.2** (published 2025-11-26) · MIT license · 0 weekly downloads

## Install

```sh
npm install nw-mwa
pnpm add nw-mwa
yarn add nw-mwa
bun add nw-mwa
```

## Health

**Score 60/100 (C)** — status: stable.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads; pre 1.0.

## Facts

| | |
|---|---|
| Version | 0.3.2 |
| Published | 2025-11-26 |
| First published | 2022-04-01 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Node | >=10 |
| Dependencies | 0 |
| Unpacked size | 45.2 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | 刘诗川 |
| Maintainers | guoyeeg, azgaga, liushichuan, yaochen, shenyuan, aflyermin, ignous, jeekdong, yousy, luofeiyue, whiskeyi, fechen |

## Links

- npm: https://www.npmjs.com/package/nw-mwa
- npm.io page: https://npm.io/package/nw-mwa

## Recent versions

- 0.3.2 (latest) — 2025-11-26
- 0.3.1 — 2025-11-24
- 0.3.0 — 2025-11-24
- 0.2.4 — 2025-11-12
- 0.2.3 — 2024-07-12
- 0.2.2 — 2024-07-11
- 0.2.1 — 2024-07-09
- 0.2.0 — 2022-04-01

## README

# nw-mwa
多WebView页面共存App通信SDK(`nw-multi-webview-app-communication`)

## 背景
- LOFTER等业务支持使用新WebView打开指定H5 url的能力，这种能力相比直接的`location.href`跳转，在维持页面状态，支持手势滑动以及页面出入场动画方面有着更好的表现
- 但是多Webview页面之间的协同通信是一个需要解决的问题，因为WebView页面A的关闭和操作，WebView页面B是无法直接感知的
- 因此，需要一个通信SDK，让两个WebView页面之间的通信能够更加灵活，更加方便

## 原理
利用多WebView之间localStorage是实时共享的机制，并且借助`storage`的`onchange`事件，实现WebView页面之间的通信

## 使用
```typescript
import { addMwaListener, removeMwaListener, triggerMwaEvent, Message } from 'nw-mwa'
import { useEffect } from 'react'
// WebView页面A
useEffect(() => {
  // 方式1: 使用返回的 remove 方法移除特定监听器（推荐）
  const listener = addMwaListener('addressSelect',(data: Message) => {
    console.log(data);  
    if (data.url === 'https://b.html') {
      console.log('用户选择的地址是：', data.data.address);
    }
  })
  return () => {
    listener.remove()
  }
  
  // 方式2: 使用 removeMwaListener 移除该事件的所有监听器
  addMwaListener('addressSelect', fn)
  
  // 删除所有监听
  removeMwaListener('addressSelect')
})


// WebView页面B
triggerMwaEvent('addressSelect', {
  address: '北京市海淀区上地十街10号'
})
```

## 注意事项
- `addMwaListener` 返回一个包含 `remove()` 方法的对象，可以用于移除特定的监听器
- `removeMwaListener` 会移除指定事件的所有监听器
- 监听到事件回调后，回调参数中同时含有消息的发送时间以及发送消息的页面URL，**可以用来判断消息是否是来自于指定页面**
- 注意及时调用`removeMwaListener`或使用返回的`remove()`方法移除监听，否则可能会导致事件错乱

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