2012-09-12 55 views
0

我在说的网站:https://sephir.ch/vfi/user/lernendenportal/index.cfm为什么不能通过JS在本网站访问元素?

我想做一个简单的书签,它填写我的电子邮件和密码到这两个文本框。我的JS代码适用于任何其他网站,但不适用于此网站。

HTML:

<input type="text" name="email" size="40" maxlength="60" class="tdschwarz" autocomplete="off"> 

JS:

javascript:function fill() {alert(document.getElementsByName("email")[0].value);} fill(); 

错误:

Uncaught TypeError: Cannot read property 'value' of undefined 

难道你们有什么想法,为什么它不工作?提前致谢。

回答

2

由于电子邮件字段位于一个框架内,因此document对象与该字段的对象不相同。

为了访问该字段,首先必须获取它所属的文档对象。检查DOM,你要访问的#mainFrame框架:

var frame = document.getElementsByName("mainFrame")[0]; 

现在你可以得到元素:

var email = frame.contentDocument.getElementsByName("email")[0]; 

这工作在现代浏览器。在IE8及以上,有这个漂亮的document.frames特性,可以使事情变得更加容易:

var email = document.frames.mainFrame.document.getElementsByName("email")[0]; 
+0

好了,我现在感觉非常愚蠢的。非常感谢。 – dislick

+0

@dislick不要觉得愚蠢。当涉及到框架网站时,这是一个普遍的疏忽。没有人真的期待他们(除了,也许,谷歌网络应用程序),特别是当他们看起来不像它。 – MaxArt

1

输入是在iframe。您需要先获取iframe,然后获取输入元素。

document.getElementsByName('mainFrame')[0].contentDocument.getElementsByName('email')[0] 
2

window.mainFrame.document得到它:

javascript:function fill() {alert(window.mainFrame.document.forms['login'].email.value);} fill(); 
相关问题