javascript 自动点击html按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12149141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Automatic click html button
提问by Fajkowsky
I am making a chrome extension and I am stuck with javascript and pressing button on page. I have site with form like this on web(isn't mine so i can't edit it):
我正在制作一个 chrome 扩展程序,但我坚持使用 javascript 并在页面上按下按钮。我在网上有这样的表单的网站(不是我的,所以我无法编辑它):
<input class="button" name="accept" type="submit" value=LoggIn">
And now I automatically open page with username and password filled but now I want that button will be clicked automatically.
现在我会自动打开填充了用户名和密码的页面,但现在我希望该按钮会被自动点击。
Thx for help!
谢谢你的帮助!
Edit:
编辑:
I have code of script:
我有脚本代码:
var tabID = 1;
chrome.tabs.create({index:tabID,url:"https://monostudby4frd.hisf.no:8001/",active:false,pinned:true},
function(tab) {
tabID = tab.id;
});
sleep(3000);
chrome.tabs.executeScript(null, {code:clickButton()});
sleep(3000);
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.remove(tabID);
});
function sleep(ms) {
var dt = new Date();
dt.setTime(dt.getTime() + ms);
while (new Date().getTime() < dt.getTime());
}
function clickButton() {
document.getElementById("accept").click();
}
And debugger says:
调试器说:
Uncaught TypeError: Cannot call method 'click' of null
回答by Zirak
Button inputs are simple: inputElem.click()
按钮输入很简单: inputElem.click()
回答by Greg Ross
You can use jquery to trigger a click event.
您可以使用 jquery 来触发点击事件。
You shouldn't really be auto-submitting a form, though.
不过,您不应该真正自动提交表单。
<form onsubmit='doSomething();'>
<input id="submitButton" class="button" name="accept" type="submit" value="LoggIn">
</form>
<script type="text/javascript">
function doSomething() {
console.log("Clicked!");
}
$("#submitButton").trigger('click');
</script>