Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
JavaScript Windows and iFrames
<!DOCTYPE html>
<html>
<head>
<title>Parent Window</title>
</head>
<body>
<label>Avatar</label>
<br/>
<input type="text" name="avatar" readonly>
<br/>
<a href="#" id="picker">Choose avatar</a>
<script>
// https://www.youtube.com/watch?v=cmA-IyD8_BA
var picker = document.getElementById('picker');
// https://javascript.info/popup-windows
picker.addEventListener('click', function() {
// https://stackoverflow.com/a/11313219/2732184
window.open('picker.html', 'Picker', 'width=400,height=300');
});
window.addEventListener("message", (event) => {
if (event.origin !== window.origin) {
alert("Cross Site Request Forgery (XSRF) from " + event.origin);
return;
}
// console.log({"source": event.source, "data": event.data});
if(event.data.action == "avatarSelected") {
document.getElementsByName('avatar')[0].value = event.data.avatar.url;
}
}, false);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Picker</title>
</head>
<body>
<label>Avatar</label>
<br/>
<small>https://via.placeholder.com/300</small>
<br>
<button id="chooser">Choose avatar</button>
<script>
var chooser = document.getElementById('chooser');
// https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
chooser.addEventListener('click', function() {
window.opener.postMessage({
action: 'avatarSelected',
avatar: {
url: 'https://via.placeholder.com/300',
}
}, window.opener.origin);
window.close();
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment