【问题标题】:Pass value to Child window using Javascript使用 Javascript 将值传递给子窗口
【发布时间】:2018-03-13 12:00:14
【问题描述】:

我正在尝试从父页面获取question id 并将其传递到我的新子页面。当子窗口得到响应时,它会将这些数据放入text_body id。我设法创建了question id 并打开了一个新窗口。但是,将值传递给 text-body id 时出现错误。

无法将属性“值”设置为 null。

我认为问题的发生是因为 JavaScript 仍然检测到前一页,并且无法聚焦到新窗口。我在下面包含了我的源代码。

function wait(ms){
    var start = new Date().getTime();
    var end = start;
    while(end < start + ms) {
        end = new Date().getTime();
    }
}

var body = document.getElementById('question').innerText;
alert(body);

var k = window.open("http://testing/support");
wait (2000);
k.focus();
wait (1000);
k.focus();
k.document.getElementById('text_body').value = body;

【问题讨论】:

标签: javascript new-window


【解决方案1】:

由于跨域限制,浏览器已经限制了打开弹出窗口和 iframe 的安全性。

您收到Cannot set property 'value' of null 的原因是您尝试运行代码以直接从 javascript 打开一个窗口 - 无需任何用户操作。。 p>

这会阻止代码正确运行,所以nullk子窗口)上的'value'(属性或变量)是你的错误;在您尝试设置变量 'value' 时,k 为空。

浏览器将以不同的方式请求允许弹出窗口的权限。如果用户没有点击任何东西来请求弹出窗口,则还没有授予允许它的权限。

下面的示例代码演示了初始调用打开window 并在没有用户操作的情况下设置子变量的错误,但是当用户单击某物时(本例中为div),确认权限后打开。

打开控制台窗口,刷新页面,你会看到非交互调用的错误。

演示的工作部分使用一个初始值显示在child window中,然后在1.5秒后,parent将调用child中的一个函数来更新显示,最后,@ 987654332@ 将访问child variable 并直接设置显示。

计时器只是为了清楚地看到发生的变化。

希望这涵盖了您正在尝试做的事情...

parentPage.html:

<html>

<head>
    <title>Parent Page</title>
</head>

<body>
    <div id="divQuestion" onclick="openChild()">Parent text</div>

    <script>
        function openChild() {
            var parentText = document.getElementById("divQuestion").innerText;
            var win = window.open("childPage.html");

            // Call a function in the child window...    
            setTimeout(function () { win.changeValue(parentText) }, 1500);

            // Directly use a variable in the child window...
            setTimeout(function () { win.childText.innerText = body + " and some more..." }, 3000);
        }

        // By calling directly you are attempting to open a child window 
        // without user permission - this will fail.
        // openChild();
    </script>
</body>

</html>

childPage.html:

<html>

<head>
    <title>Child Page</title>
</head>

<body>
    <div id="divText">Child text</div>

    <script>
        var childText = document.getElementById("divText");

        function changeValue(val) {
            // Take a value from elsewhere (parent window in this case) and update the div
            childText.innerText = val;
        }
    </script>
</body>

</html>

【讨论】:

    猜你喜欢
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多