Several questions have been asked about how to access a global variable in an iframe. I'd like to know how to declare and initialize a global variable in an iframe's scope from the parent. I know I can access the variable from the iframe using document.myGlobalVariable, but I'd like to be able to reference it just by saying myGlobalVariable, without document. in the front.
Here's my HTML:
<html>
<head>...</head>
<body>
...
<iframe src="myFrame.html"></iframe>
<script type="text/javascript">
var iframe = document.querySelector('iframe');
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
iframeDocument.myGlobalVariable = "Hello";
</script>
</body>
</html>
myFrame.html
<html>
<body>
...
<script type="text/javascript">
// wait for document to load so parent script can finish running
$(function() {
console.log(document.myGlobalVariable); // <-- This works
console.log(myGlobalVariable); // <-- But this doesn't (and I want this one)
});
</script>
</body>
</html>
Thanks!