在新窗口中获取元素

时间:2018-03-25 15:23:35

标签: javascript

我正在尝试在新打开的窗口中获取一个元素(或者在我的情况下为tab),但我不能这样做。

我的想法是在加载后立即打开网站,输入我的用户名和密码进行登录。

我尝试了以下代码:

var site = open("site url");
user = site.document.getElementById("username");
user.value = "myUsername";

控制台显示错误:

  

未捕获的TypeError:无法将属性'value'设置为null。

我尝试使用setTimeout.onload,但它也无效

任何人都可以帮助我吗?

我知道这看起来很简单,但我刚开始用JavaScript编程,我还在学习。

1 个答案:

答案 0 :(得分:0)

让我们考虑两个HTML文件:

openwindow.htm - 它有一个文本框和一个按钮,单击该按钮可在新的浏览器窗口中打开target.htm文件 target.htm - 这个代码可以更改打开此文件的父窗口(openwindow.htm)中存在的文本框的值

openwindow.htm:

<html>
<script language="javascript">
      function openwindow()
      {
          window.open("target.htm","_blank","height=200,width=400,
          status=yes,toolbar=no,menubar=no,location=no")
      }
</script>
<body>
      <form name=frm>
          <input id=text1 type=text>
          <input type=button onclick="javascript:openwindow()" value="Open window..">
      </form>
</body>
</html>

请注意,如果未提供参数“_blank”,则IE和Firefox之间的功能会有所不同,在firefox中将打开一个新选项卡而不是新窗口。只需使用window.open(&#34; target.htm&#34;)并自己查看差异。有关window.open()方法及其参数的更多信息,请参阅http://msdn2.microsoft.com/en-us/library/ms536651(VS.85).aspx。另请注意,在id属性中,只需要在Firefox中执行target.htm(如下所示)的代码。

target.htm:

<html>
<script language="javascript">
     function changeparent()
     {
          window.opener.document.getElementById('text1').value="Value changed.."
     }
</script>
<body>
     <form>
          <input type=button onclick="javascript:changeparent()" value="Change opener's textbox's value..">
     </form>
</body>
</html>

在这里,我已经向您展示了孩子正在访问父窗口,但您也可以这样做。

相关问题