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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With