开发者

JavaScript: Why is it so with windows.parent?

Why is it so that when you use window.parent.showMessage("Video Is OK"); inside a .js file you've included on a page, it won't work, but on开发者_运维知识库ly if it's on the page itself..?

Can you fix this?


There are two scenarios that I can think of where you'd want to use window.parent. The first is when you have a window open another window using window.open. The other is where the first window uses an iframe to load a page. In the former case, it appears as though you actually want to use window.opener, as ukostin has said. In the latter case, window.parent works fine. Both methods work properly 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>


Try to use window.opener as link to the parent window.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜