Created
January 9, 2020 19:08
-
-
Save tripolskypetr/b3671273af7282836d924e0ae860b0dd to your computer and use it in GitHub Desktop.
The State Reducer Pattern between separated windows (window.open)
This file contains 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Frame</title> | |
</head> | |
<body> | |
<button>Send message</button> | |
<script> | |
(function() { | |
const ACTION = { | |
SHOW_ALL: 'SHOW_ALL', | |
SHOW_COMPLETED: 'SHOW_COMPLETED', | |
SHOW_ACTIVE: 'SHOW_ACTIVE' | |
} | |
const handler = ({origin, data}) => { | |
if (origin !== url) { | |
return; | |
} | |
switch (data) { | |
case ACTION.SHOW_ALL: | |
alert('Show all'); | |
break; | |
case ACTION.SHOW_COMPLETED: | |
alert('Completed'); | |
break; | |
case ACTION.SHOW_ACTIVE: | |
alert('Show active'); | |
break; | |
default: | |
throw new Error(`Invalid action ${JSON.stringify(data)}`); | |
} | |
} | |
const { protocol, host, hash, href } = location; | |
const url = `${protocol}//${host}`; | |
const target = hash === "#child" ? opener : open(location.href + "#child"); | |
window.addEventListener('message', (e) => handler(e)); | |
document.querySelector('button').addEventListener('click', () => | |
target.postMessage(ACTION.SHOW_ALL) | |
); | |
})(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment