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):
<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
Button inputs are simple: inputElem.click()
You can use jquery to trigger a click event.
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>
Related
I have some simple code...
HTML:
<form>
<input type="text" placeholder="Search.." id='query'>
<button type="button" name="submitButton" id="submitBtn2" onclick="submitBtn()">SEND</button>
</form>
<iframe id="results" name="results" onload='javascript:resizeIframe(this);' src="javascript:void(0);"></iframe>
Javascript:
<script language="javascript" type="text/javascript">
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
</script>
<script language="javascript" type="text/javascript">
function submitBtn() {
var search = document.getElementById('query').value;
console.log("search:" +search);
console.log(search.length)
if (search.length>0){
document.getElementById('results').src = 'data:text/html;charset=utf-8,' + escape('<h2>'+ search +'</h2>');
userAction(search);
}
}
</script>
<script language="javascript" type="text/javascript">
function userAction(res) {
var request = new XMLHttpRequest();
var api = 'myAPI';
var url= api + res;
request.open('GET', url, true);
request.onload = function () {
var data = this.response;
if (request.status >= 200 && request.status < 400) {
document.getElementById('results').src = "data:text/html;charset=utf-8," + escape(data);
} else {
console.log('error');
}
}
request.send();
}
</script>
Issue:
If I have a blank query field - then everything works as it should when I click the button (not changing anything - and I can see the logs from inside submitBtn()), however if I enter a value into the query field then when I click the button, it does not trigger my submitBtn() function.
Instead it redirects my url to "mycurrenturl"/? - I am not sure why it does this and adds /? to the end of my url.
The api I am trying to hit is an Azure functions HttpTrigger. I do not get the console.logs from within my submitBtn() function, so I am assuming it is an issue with the form when there is a value inputted?
Any help would be much appreciated.
Thanks!
The problem is only happening when you press Enter in the text field. That submits the form, it doesn't trigger a click on the button. The solution is to use the form's onsubmit handler:
<form onsubmit="submitBtn(); return false;">
return false; prevents the default submission action from happening.
If you do this, you can also remove the onclick from the submit button, and change it to type="submit". Then clicking on the button will trigger a form submit, which will then run the above code.
I have a script which gets a form with fields filled by itself, and I got a code that submits the form automatically every x second(s).
The problem is that I added this attribute (target="_blank") to the form, but the form kept on executing the code and creating a new tab infinitely.
I want my script to create a new tab for processing the form and the second time my script executes, to use the same tab to refresh the processing page.
Can I do that in JavaScript?
<form target="_blank" name="myForm" id="myForm" action="process.asp" method="post">
field 1:<input type="text" name="field1" id="field1" /><br>
field 2:<input type="text" name="field2" id="field2" /><br>
</form>
<script type="text/javascript"> // code which executes the submit of form operation
window.onload=function(){
var auto = setTimeout(function(){ autoRefresh(); }, 100);
function submitform(){
document.forms["myForm"].submit();
}
function autoRefresh(){
clearTimeout(auto);
auto = setTimeout(function(){ submitform(); autoRefresh(); }, 10000);
}
}
</script>`
Please Try with this code (Using Ajax). It will help you with ajax and it not open any new tab and help to submit form with Last Updated Date and Time.
It work on My Base.
Please Try it with Your Code.
<html>
<head>
</head>
<body>
<form target="_self" name="myForm" id="myForm" action="process.asp" method="post">
field 1:<input type="text" name="field1" id="F1" />
<br>
field 2:<input type="text" name="field2" id="F2" />
<br>
<p id="LastDt"></p>
</form>
<script type="text/javascript"> // code which executes the submit of form operation
window.onload = function () {
var auto = setTimeout(function () {
autoRefresh();
}, 100);
function submitform() {
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("LastDt").innerHTML = "Last Update : " + new Date();
}
};
// It send data on process.asp (silently).
xmlhttp.open("POST", "process.asp?field1=" + document.getElementById("F1").value + "&field2=" + document.getElementById("F2").value , true);
xmlhttp.send();
}
function autoRefresh() {
clearTimeout(auto);
auto = setTimeout(function () {
submitform();
}, 10000);
}
}
</script>
</body>
</html>
You could add same form in process.asp and after the first submit opens the new tab...use postMessage API to pass data to other tab and have it submit from there.
Or you could store the data in localStorage and use storage events in process.asp to listen for updates and post the data
I'm trying to get my form to not submit when I press the cancel button on my JavaScript dialog.
I have this code:
$(document).ready(function() {
$("#submit").click(function (e) {
e.preventDefault();
var link = $(this).attr("href"); // "get" the intended link in a var
var result = confirm("Are you sure you want to log this fault?");
if (result) {
document.location.href = link; // if result, "set" the document location
}
});
});
The form submits regardless if I press the Ok or Cancel buttons or not even though I have the prevent default code.
My HTML code is:
<button type="submit" id="submit" class="btn btn-default"><span class="glyphicon glyphicon-floppy-save"></span></button>
<form id="myform" method="post" action="/the/post/url">
<!-- other elements -->
....
....
....
<button type="submit" id="submit" class="btn btn-default">
<span class="glyphicon glyphicon-floppy-save"></span>
</button>
</form>
$(function() {
//this would do the same as button click as both submit the form
$(document).on("submit", "#myform", function (e) {
var result = confirm("Are you sure you want to log this fault?");
//if cancel is cliked
if (!result) {
return false;
}
//if ok is cliked, form will be submitted
});
});
the following like won't work since this reffers to the submit button which does not have an href attribute.
var link = $(this).attr("href"); // is invalid.
try
$(document).ready(function() {
$("#submit").click(function (e) {
e.preventDefault();
var result = confirm("Are you sure you want to log this fault?");
if (result) {
$('#formId').submit(); // where formId is the id of your form
document.location.href = "url to which you want to redirect";
}
else
return false;
});
});
side note: from wherever you got this piece of code, they must be using a hyperlink <a> styled like a button, with a valid href attribute :)
I have a code here for disabling the radio on a form and focusing on the submit button right after the timer expires. But this code seems not to work. Can you tell me what's wrong with my code or if you have any alternative with this? I'm using jquery timeTo plugin as my timer ..
<script type="text/javascript">
$(document).ready(function() {
$('#countdown').timeTo(5000, disablefocus();
});
});
function disablefocus(){
$(document).ready(function() {
$('input[type=radio]').attr('disabled', true);
$('#submitWidget').focus();
});
</script>
---->
<div id='countdown'></div>
<form>
<input type='radio' name='radio1' value='father'>
<input type = 'submit' id ='submitwidget' value='submit'/>
</form>
you add extra curly braces for timeTo function and miss the closed curly braces for disableFocus function.
$(document).ready(function() {
$('#countdown').timeTo(5000, disablefocus);
function disablefocus(){
$('input[type=radio]').attr('disabled', true);
$('#submitWidget').focus();
}
});
or another way
$('#countdown').timeTo(5000, function() { disablefocus(); });
$(document).ready(function() {
$('#countdown').timeTo(20, function() {
disablefocus();
});
function disablefocus(){
var message = $('#confirmMessage');
var goodColor = "#66cc66";
$('input[type=radio]').attr('disabled', true);
$('#submitWidget').focus();
message.css("color" , goodColor);
message.html("Press me now!");
}
});
i have a simple javascript i use to feed a DIV with content from a script using AJAX. This happens only after the user clicks a button. What i want after the user pressed the button (once) and the DIV is filled with de output of the script:
disable the button
have the DIV to reload the script's output every 5 seconds using AJAX
< script language="Javascript">
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
updatepage(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send(getquerystring());
}
function getquerystring() {
var form = document.forms['f1'];
var xword = form.xword.value;
qstr = 'addpost=' + escape(xword); // NOTE: no '?' before querystring
return qstr;
}
function updatepage(str){
document.getElementById("result").innerHTML = str;
}
</script>
<form name="f1">
<input name="xword" type="hidden" value="someword">
<input value="betaling gereed" type="button" name="btn" onclick='JavaScript:xmlhttpPost("script.php")'></p>
<div id="result"></div>
</form>
use setTimeout() javascript method as follows:
setTimeout ('xmlhttpPost("script.php")', 5000);
At the end of your updatepage() method, call this.
For example:
function updatepage(str){
document.getElementById("result").innerHTML = str;
setTimeout ('xmlhttpPost("script.php")', 5000);
}
To disable the button, you will need to add an id attribute to your button tag. Then you can disable like so:
document.getElementById('btn').disable();
To repeat the ajax call indefinitely:
var refresh = false,
btn = document.getElementById("btn");
btn.onclick = function(){
refresh = true;
this.disable();
fetchData("script.php");
}
function fetchData(strURL){
while(refresh){
setTimeout(xmlhttpPost(strURL), 5000);
}
}
And:
<form name="f1">
<input name="xword" type="hidden" value="someword">
<input value="betaling gereed" type="button" id="btn" name="btn"></p>
<div id="result"></div>
</form>
You are looking for JS Time Events?
w3shools jvascript time events
onclick="setInterval(func(), 5000)"
ok Edit:
i didnt test it, is to late
<input id="loadStuffButton" value="betaling gereed" type="button" name="btn" onclick='setInterval(xmlhttpPost("script.php"), 5000);'></p>
function xmlhttpPost(strURL) {
document.getElementById('loadStuffButton').disabled = true;
....
}
Edit 2: Test This
Quick and dirty without Ajax to show how setIntervalworks with 5 ms hehe
<form name="f1">
<input name="xword" type="hidden" value="someword">
<input id="loadStuffButton" value="betaling gereed" type="button" name="btn" onclick='setInterval(function(){xmlhttpPost("script.php")}, 500);'></p>
<div id="result">
test
</div>
</form>
<script>
i = 1;
function xmlhttpPost(strURL) {
document.getElementById('loadStuffButton').disabled = true;
updatepage(i++);
}
function updatepage(str){
document.getElementById("result").innerHTML = str;
}
</script>