Created
May 2, 2019 05:19
-
-
Save miguelmota/d64289e8eb2b9ea12d3dd683ec55eee2 to your computer and use it in GitHub Desktop.
JavaScript popup window message passing example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
const windowName = 'MyApp' | |
const options = 'location=0,status=0,width=800,height=400' | |
const path = 'http://localhost:9000/auth' | |
const child = window.open(path, windowName, options) | |
let myValue = '' | |
let messagePosted = false | |
window.addEventListener('message', event => { | |
if (event.data.complete) { | |
myValue = event.data.myValue | |
child.close() | |
} | |
}) | |
const interval = setInterval(() => { | |
if (!messagePosted) { | |
child.postMessage({domain: window.location.host}, '*') | |
messagePosted = true | |
} | |
if (child.closed) { | |
clearInterval(interval); | |
callback(null, {username}) | |
} | |
}, 100) | |
</script> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
const form = document.querySelector('#form') | |
const input = document.querySelector('#input') | |
window.addEventListener('message', event => { | |
if (event.data.domain) { | |
domain.innerHTML = event.data.domain | |
} | |
}) | |
form.addEventListener('submit', event => { | |
event.preventDefault() | |
const data = {complete: true, myValue: input.value} | |
window.opener.postMessage(data, '*') | |
}) | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment