Skip to content

๐Ÿš€ Asynchronous iframe communication based on postMessage

License

Notifications You must be signed in to change notification settings

pxs797/async-messenger

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

12 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

async-messenger

๐Ÿš€ Synchronized communication between windows and iframes

Installing

Package manager

Using npm:

$ npm install @pengxs/asyn-messenger

Using yarn:

$ yarn add @pengxs/async-messenger

Using pnpm:

$ pnpm add @pengxs/async-messenger

Example

parent.html

<html>
<body>
  <iframe id="child" src="child.html" frameborder="0"></iframe>

  <script type="module">

    import asyncMessenger from '@pengxs/async-messenger'

    const child = document.querySelector('#child')
    child.onload = async () => {
      const messenger = asyncMessenger.create({target: child.contentWindow})
      const res = await messenger.post({event: 'say'})
      console.log(res) // Hello World
    }

  </script>

</body>
</html>

child.html

<html>
<body>

  <script type="module">

    import asyncMessenger from '@pengxs/async-messenger'

    const messenger = asyncMessenger.create({target: window.parent})
    window.addEventListener('message', async (e) => {
      const { data, channel } = e.data
      if (data.event == 'say') {
        messenger.send({ channel, data: 'Hello World' })
      }
    })

  </script>

</body>
</html>

License

MIT License ยฉ 2023 Mark Peng

About

๐Ÿš€ Asynchronous iframe communication based on postMessage

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published