我想从其他网站填写表格,但出现错误,而且我不明白原因。
我的JS的功能:
<script type="text/javascript">
function rempliFormulair(url) {
var fenetrePopup = window.open(url);
fenetrePopup.getElementsByName("NameText").value = "MyLogin";
fenetrePopup.getElementsByName("NameForm").submit();
}
</script>
这是我的表格:
<form name = "NameForm" class="" action="index.html" method="post">
<input id = "idText" type="text" name="NameText" value="">
<input id = "azee" type="submit" name="submit" value="aze">
</form>
我的错误:
Uncaught TypeError: fenetrePopup.getElementsByName is not a function at rempliFormulair
最佳答案
Uncaught TypeError: fenetrePopup.getElementsByName is not a function at rempliFormulair
fenetrePopup
是对 pop-window 对象的引用。您需要访问同一文档中的 document
对象。另外您只能访问文档if the origin is same .
其次,getElementsByName
返回一个 NodeList
,
尝试
fenetrePopup.document.getElementsByName("NameText")[0].value = "MyLogin";
fenetrePopup.document.getElementsByName("NameForm")[0].submit();
或使用querySelector
var doc = fenetrePopup.document;
doc.querySelector("[name='NameText']").value = "MyLogin";
doc.querySelector("[name='NameForm']").submit();
注意
仅当 url
位于同一来源时,此功能才有效。
编辑
还需要等待子window
的onload
事件
fenetrePopup.onload = function(){
var doc = fenetrePopup.document;
doc.querySelector("[name='NameText']").value = "MyLogin";
doc.querySelector("[name='NameForm']").submit();
};
关于javascript - 从另一个网站JS填写表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47903410/