Skip to content

Instantly share code, notes, and snippets.

@VitorLuizC
Last active February 8, 2018 13:55
Show Gist options
  • Select an option

  • Save VitorLuizC/9538e34c41c46557ea6b8aa5b02fa52d to your computer and use it in GitHub Desktop.

Select an option

Save VitorLuizC/9538e34c41c46557ea6b8aa5b02fa52d to your computer and use it in GitHub Desktop.
Função de comunicação com um <iframe> ou WebWorker que aguarda a confirmação do recebimento da mensagem. Tem também um exemplo de como usar num aplicativo Vue.js dentro de uma <iframe>.
/**
* Envia uma mensagem para o <iframe> ou WebWorker.
* @param {Window} window
* @param {string} type
* @param {Array.<string>} payload
* @returns {Promise.<boolean>}
*/
export default function comunicate (window, type, payload) {
let timeout = null
const url = document.location
const time = 1000 * 3
return new Promise((resolve) => {
const done = () => {
window.removeEventListener('message', handler)
clearTimeout(timeout)
resolve(true)
}
const handler = (event) => {
const [ messageType ] = event.data || []
if (messageType !== type)
return
done()
}
const send = () => {
window.postMessage([ type, ...payload ], url)
timeout = setTimeout(send, time)
}
window.addEventListener('message', handler)
send()
})
}
<template>
<router-view></router-view>
</template>
<script>
export default {
methods: {
handler (event) {
const [ type, status, ...payload ] = event.data || []
if (!type || status === 'received')
return
window.postMessage([ type, 'received' ])
this.$store.dispatch(type, [ status, ...payload ])
}
},
beforeDestroy () {
window.removeEventListener('message', this.handler)
},
mounted () {
window.addEventListener('message', this.handler)
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment