JavaScript: An exception that occurred in the parent window occurs in the child window

I ran into a problem that confused me. We all know that multiple browsers (tabs) that have the same origin can share JavaScript resources.

So, I made a parent window that opens a child window through window.open . A child window calls a global function in the parent window through window.opener.functionName . Take a look at the 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 this: you can find the result of console.log in the parent.html window, but this exception thrown in the parent window will appear strange in the child.html window. This bothers me, I need this exception in the parent window due to the BDD test. How can i do this?

Sorry for my poor English, feel free to correct my grammatical errors.

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

I found a solution to this question using the HTML5 postMessage function. But I'm still curious why this is happening. What excludes an exception from the parent window to the child window? Any inspiration is appreciated.

+6
source share
1 answer

I figured out the solution myself. The solution is easy: in the child window informs the parent window to call the function through postMessage . It works the way I want it. I caught an exception in the parent window.

+1
source

Source: https://habr.com/ru/post/955486/


All Articles