首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在点击新链接后从子窗口访问父窗口

在点击新链接后从子窗口访问父窗口,可以通过以下步骤实现:

  1. 在父窗口中创建一个全局变量,用于存储子窗口的引用。
  2. 在点击链接时,通过JavaScript的window.open()方法打开一个新的子窗口,并将子窗口的引用赋值给父窗口中的全局变量。
  3. 在子窗口中,可以通过window.opener属性访问父窗口的对象。
  4. 在子窗口中,可以使用window.opener对象调用父窗口中的方法或访问父窗口中的变量。

以下是一个示例代码:

在父窗口中的HTML代码:

代码语言:html
复制
<!DOCTYPE html>
<html>
<head>
    <title>父窗口</title>
    <script>
        var childWindow; // 全局变量,用于存储子窗口的引用

        function openChildWindow() {
            childWindow = window.open("child.html", "_blank");
        }

        function accessParentWindow() {
            if (childWindow && !childWindow.closed) {
                childWindow.postMessage("Hello from parent window!", "*");
            }
        }

        function receiveMessage(event) {
            if (event.origin !== window.location.origin) {
                return;
            }

            console.log("Message received from child window: " + event.data);
        }

        window.addEventListener("message", receiveMessage, false);
    </script>
</head>
<body>
    <button onclick="openChildWindow()">打开子窗口</button>
    <button onclick="accessParentWindow()">从子窗口访问父窗口</button>
</body>
</html>

在子窗口中的HTML代码(child.html):

代码语言:html
复制
<!DOCTYPE html>
<html>
<head>
    <title>子窗口</title>
    <script>
        function accessParentWindow() {
            if (window.opener && !window.opener.closed) {
                window.opener.postMessage("Hello from child window!", "*");
            }
        }
    </script>
</head>
<body>
    <button onclick="accessParentWindow()">从子窗口访问父窗口</button>
</body>
</html>

在上述示例中,父窗口中的openChildWindow()函数用于打开子窗口,accessParentWindow()函数用于从子窗口访问父窗口。子窗口中的accessParentWindow()函数用于从子窗口访问父窗口。

注意:为了确保安全性,可以在父窗口和子窗口之间进行消息传递时使用window.postMessage()方法,并通过事件监听器在父窗口中接收消息。这样可以避免跨域安全问题,并确保只有受信任的消息才能被处理。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

  • 领券