Skip to content

Instantly share code, notes, and snippets.

@trkaplan
Last active February 14, 2021 18:34
Show Gist options
  • Save trkaplan/db5a9d0ec56fba2ff4ec22d0e236493d to your computer and use it in GitHub Desktop.
Save trkaplan/db5a9d0ec56fba2ff4ec22d0e236493d to your computer and use it in GitHub Desktop.
Accessing variables in parent window from iframe
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>iframe</title>
</head>
<body>
<h1>iframe </h1>
</body>
<script>
const { a, b, c, d, e } = top;
console.log({ a, b, c, d, e })
// result: {a: 1, b: 2, c: 3, d: undefined, e: undefined}
</script>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Accessing variables in parent window from iframe.</h1>
<p><b>let</b> and <b>const</b> variables return <b>undefined</b> because they are block scoped while others are
globally scoped.</p>
<iframe height="555px" src="accessing_variables_from_iframe_iframe.html" frameborder="0"></iframe>
</body>
<script>
a = 1;
window.b = 2;
var c = 3;
let d = 4;
const e = 5;
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment