0.2.0 • Published 2 years ago

nw-mwa v0.2.0

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

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是实时共享的机制,并且借助storageonchange事件,实现WebView页面之间的通信

使用

import { addMpaListener, removeMpaListener, triggerMpaEvent, Message } from 'nw-mwa'
import { useEffect } from 'react'
// WebView页面A
useEffect(() => {
  addMpaListener('addressSelect', (data: Message) => {
    console.log(data);
    if (data.url === 'https://b.html') {
      console.log('用户选择的地址是:', data.message.address);
    }
  })
  return () => {
    removeMpaListener('addressSelect')
  }
})


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

注意事项

  • 为防止事件错乱,一个页面对同一个事件名称只能同时存在一个监听器,后注册的会覆盖前者,所以移除事件监听也无需传递监听器函数
  • 监听到事件回调后,回调参数中同时含有消息的发送时间以及发送消息的页面URL,可以用来判断消息是否是来自于指定页面
  • 注意及时调用removeMpaListener移除监听,否则可能会导致事件错乱