JavaScript: Why is this the case with windows.parent?

Why is it so that when you use window.parent.showMessage("Video Is OK"); inside the .js file that you included on the page, it will not work, but only if it is on the page itself ..?

Can you fix it?

+4
source share
2 answers

There are two scenarios in which I can think about where you want to use window.parent . First, when you have a window, open another window using window.open . Otherwise, the first window uses an iframe to load the page. In the first case, it seems that you really want to use window.opener , as ukostin said. In the latter case, window.parent works fine. Both methods work correctly, whether the code is inline or loaded from an external JS file. Here are some tests:

Popup

parentWindow.htm:

 <html> <head> <script>function showMsg(msg){alert(msg);}</script> <body> <a href="#" onclick="window.open('childWindow.htm','child','width=300,height=100')">Open</a> </body> </html> 

externalWindow.js:

 function showMsgExternal(msg){window.opener.showMsg(msg);} 

childWindow.htm:

 <html> <head> <script>function showMsgInline(msg){window.opener.showMsg(msg);}</script> <script src="externalWindow.js"></script> </head> <body> <a href="#" onclick="showMsgInline('inline')">Inline</a> <a href="#" onclick="showMsgExternal('external')">External</a> </body> </html> 

IFRAME

parentFrame.htm:

 <html> <head> <script>function showMsg(msg){alert(msg);}</script> </head> <body> <iframe src="childFrame.htm" width="300" height="100"></iframe> </body> </html> 

externalFrame.js:

 function showMsgExternal(msg){window.parent.showMsg(msg);} 

childFrame.htm:

 <html> <head> <script>function showMsgInline(msg){window.parent.showMsg(msg);}</script> <script src="externalFrame.js"></script> </head> <body> <a href="#" onclick="showMsgInline('inline')">Inline</a> <a href="#" onclick="showMsgExternal('external')">External</a> </body> </html> 
0
source

Try using window.opener as a reference to the parent window.

0
source

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


All Articles