Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Exception thrown in parent window occurs in child window

I came across a problem that made me confused. We all know that a couple of browsers window(tabs) which have the same origin can share JavaScript resources.

So, I made a parent window open a child window via window.open. The child window calls a global function in parent window via window.opener.functionName. Take a look at two snippets below:

parent.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <h1>Parent</h1>
</body>
<script type="text/javascript">

function sayHi(child) {
    console.log("Before throwing an error..");
    throw new Error('Some error');
}

window.open('child.html')

</script>
</html>

child.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <h1>Child</h1>
</body>
<script type="text/javascript">

window.opener.sayHi(window);

</script>
</html>

The problem is: You can find the console.log result in parent.html window, but that exception thrown in parent window will weirdly occur in child.html window. It makes me confused, I need that exception in parent window because of BDD Test. How can I make it happen?

Sorry for my poor English, feel free to correct my grammar mistakes.

========================Update======================

I have found a solution to this question, using HTML5 feature postMessage. But I am still curious why it happen. What makes the exception escape from parent window to child window? Any inspiration is appreciated.

like image 246
Jerry Avatar asked Oct 08 '13 12:10

Jerry


1 Answers

I have figured out the solution by myself. The solution is easy: In the child window, informs parent window to call the function via postMessage. It works as I want it to. I caught the exception in parent window.

like image 57
Jerry Avatar answered Oct 31 '22 22:10

Jerry