Peter Wójcik Peter Wójcik - 3 months ago 20
Javascript Question

iframe + instanceof Object FAIL

This blew my mind today, check it out:

index.html



<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>framed</title>
</head>
<body>
<iframe src="sandbox2.html" frameborder="0" width="640" height="480" id="frame"></iframe>
</body>
</html>





sandbox2.html (insides of the iframe)



<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>instanceof Object FAIL DEMO</h1>
<div id="foo"></div>
#foo.bar instanceof Object: <span id="result"></span>
<br/>
typeof #foo.bar: <span id="result2"></span>

<script>
document.addEventListener("DOMContentLoaded", function() {
document.getElementById('foo').bar = { test: 'aaa' };
setInterval(function() {
document.getElementById('result').textContent = (document.getElementById('foo').bar instanceof Object).toString();
document.getElementById('result2').textContent = (typeof document.getElementById('foo').bar).toString();
}, 100);
});
</script>
</body>
</html>





Now, open index.html, go to the developer console and type

document.getElementById("frame").contentDocument.getElementById('foo').bar = {}


typeof #foo.bar
returns
object
(and foo is actually an Object)

But
#foo.bar instanceof Object
returns false!!!!

I've tried Chrome, Firefox and MS Edge, all have the same behavior. Why is this happening? Is this some kind of bug?

Answer

change sandbox2.html to

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>instanceof Object FAIL DEMO</h1>
    <div id="foo"></div>
    #foo.bar instanceof Object: <span id="result"></span>
    <br/>
    #foo.bar instanceof parent.Object: <span id="result1"></span>
    <br/>
    typeof #foo.bar: <span id="result2"></span>

    <script>
        document.addEventListener("DOMContentLoaded", function() {
            document.getElementById('foo').bar = { test: 'aaa' };
            setInterval(function() {
                document.getElementById('result').textContent = (document.getElementById('foo').bar instanceof Object).toString();
                document.getElementById('result1').textContent = (document.getElementById('foo').bar instanceof parent.Object).toString();
                document.getElementById('result2').textContent = (typeof document.getElementById('foo').bar).toString();
            }, 100);
        });
    </script>
</body>
</html>

Now you will see that changing, from the main frame, the object in the iframe will change it from an instanceOf Object to an instanceOf parent.Object - the two are different Objects