How do I automate clicking a button in javascript? - javascript

my current work is basically clicking a button every couple of minutes and check if there are any new tickets.
With some programming background I thought this would be an easy-to-automate task, but being completely new to javascript, I'm already struggling with the "button clicking".
Unfortunately, because it is an internal website, I can't share the exact code, but I'll try to give as much information as I am able to.
I tried to "click" in the console:
'document.getElementById("IDofButton").click()'
But it gives me an error "undefined"; without the ".click()" at the end I get the correct element as a result. I tried it with "$" instead of document.getElementById, but even that didn't work, so I gave up on the idea of simply clicking the button, even though I think that's the easier way.
Debugging in chrome with breakpoints and the performance profiler, I could find the first called function "h()", it runs for 0.020 ms, then another function gets called, running for 0.012 ms and then a longer function gets called running for 14.8 ms, several others follow. My guess or better hope, was that the first two functions check something and then start the whole process. But I can't simply call any of the functions with like the following example syntax: "h()".
I'd be very glad, if anyone has an idea or could point me in the right direction.
Thank you very much.
EDIT/UPDATE:
I finally found the problem:
While debugging with the performance profiler I saw, that the functions are triggered by a mouseup event and I thought the "[...].click()" simulates a mousedown and a mouseup instead of a click.
I now copied a function simulating the whole mouseover>mousedown>mouseup>click and it works as expected.
Thank you to all who helped me with the whole situation!

You get undefined because your selector is wrong. Try learning css selectors and see if it helps you(https://www.w3schools.com/cssref/css_selectors.asp)
You can also inspect the elements in the dev tools and right clicking on the element, going to copy->Copy JS Path. This will give you the correct selector.
Also you can select the element and reference it in the dev tools console with $0.
Then if you want to re-click every second then use setInterval
setInterval(() => {
document.querySelector('#someId').click()
}, 1000)
Hope that helps you, good luck!

setInterval(
function(){
document.getElementById('IDofButton').click()
},5000)// time in milliseconds i set for 5 sec
Above time set for each 5 Seconds.
if doesn't work Let me know.

Related

How to find the place where a certain function is called?

I'm writing a webpage, where I need to do some little changes. The problem is, I need to find the place, where one certain function is called (there are plenty of JavaScript files, so I'm not able to go through them line by line). Do you have any idea, how could I find it out?
I know how to do step-by-step debugging in Firebug or similar browser consoles, but still, I don't know how to recognize the place where the function was called.
I prefer working with consoles in Firefox or Chrome.
Debugging Tips For Chrome:
There are probably a number of ways you can find out where a change is coming from. But I find this one a time saver when it comes to tracking down changes in the DOM. (which will usually lead me to a function I am looking for)
Break on subtree modification or attribute modifications. To do this right click on an element in the DOM tree. Specifically the one you think the change is being applied to. From there you will get a context menu which will give you these options. Selecting either one with set a DOM breakpoint.
If this triggers the debugger you can then proceed to step through the code by using F11 and shift + F11 to skip over functions (useful if you wind up in a library like jQuery). While doing this, pay attention to the call stack. This will tell you where the code is coming from..
More in depth information:
https://developer.chrome.com/devtools/docs/javascript-debugging
To get to know the caller of a function just set a breakpoint at the first line of it. Once the breakpoint gets hit, you can see within the stack trace from where it was called.
Firefox DevTools
Firebug
Chrome DevTools
If you have access to the scripts, you could add at the end of every function you want to watch :
console.trace()
This will output in Chrome's console what function have been called with its position in the file (line number)

How do I find what Javascript is running on certain events?

I'll pick Chrome for this example, but I'm open to a solution from any browser.
Use Case:
I have an update button on my website that is used to update item quantities in a shopping cart. I'd like to allow a user to enter a 0 and click update in order to remove the item. Trouble is, there is some listener in some js function that is denying the ability to enter a 0 and click update (after clicking update the old quantity remains).
My question is, what developer tool can I use to find which js function is running during that event? I don't think that Chrome's inspector does this, and I'm not very familiar with Firebug, but I couldn't find the functionality there either.
I feel that I should be able to inspect js firings just like I do css stylings. Is anyone aware of a tool I may use?
I've had to debug some particularly nasty unseen-cause Javascript issues at my job. Knowing the full depth of developer tools like Chrome's is definitely helpful. It undeniably takes some creativity to find places that might be causing the issue, but a few tips:
Tracking down event listeners
Under Chrome's Elements view, try Inspect-ing an element (right-click, Inspect); then, on the right side of the developer view, scroll down to Event Listeners. Here you can view what code files have hooked up an event. Often, this will just point you to a middle-framework from the really devious code you're looking for, but sometimes it will point you in the right direction.
Trapping a DOM modification
Many of the unwanted effects I see are because of something changing some value or attribute on the page that I don't want. Anytime this happens, you can right-click on the element (under the Elements view) and say "Break on..." and the specific scenario you're looking for. When Chrome then hits a breakpoint, you can then look downward in the Stack Trace until you find something recognizable that shouldn't be called.
EDIT after reaching ten votes!
Trapping a JS object modification
If the change you're interested in is code-internal, not in the UI, things get trickier. What's meant by this scenario is that you know somewhere in the code, something incredibly annoying like the following is happening.
company.data.myObject.parameter = undefined;
In this situation, you know myObject is still the same object, but it's being modified, perhaps unintentionally. For that, I often insert the following bit of code, sometimes just through the developer console at some point before said modification happens.
Object.defineProperty(company.data.myObject, 'parameter', {
set: (val) => {
debugger;
}
});
This includes an arrow function - you're only using this for debugging and Chrome supports it, so might as well save keystrokes. What this will do is freeze your debugger as soon as some line of code attempts to modify myObject's "parameter" property. You don't necessarily have to have a global reference to the variable if you can run this line of code from a previous breakpoint that will have the given object in the locals.
Otherwise, if all I'm starting out with is the HTML code, and I want to tie that to Javascript code, I'll often just look for identifying features like "id" elements, and search all JS files in my development directory for it. Normally, I can reach it pretty fast.
Open your page in Firefox with Firebug enabled.
Go to console tab in firebug and click profiling
enter 0 in the textbox and click the button.
Stop profiling.
You will be able to see all the javascript functions which have executed due to your actions. You can view them one by one to figure out which method has caused the mischief.
Go to you code. If you are using jQuery there is going to be a function that will be called with the class or id of that particular update button. Or, if you are using Javascript, there is going to be a function called inside the
<input type="button" name="update" onclick="update()">
These are the two ways to look for the function that is being called; there is no software that I know
Download Firebug for Mozilla Firefox, open it, click on Net and refresh your website. Than, you can see which files are loaded on the page.
If you want to check on errors and what goes wrong with an explanation, than click on console and refresh the page once again. You will see the errors and on which line it goes wrong.
Note: in your console, you can say hold or stop, so that the js file stops loading. And you can edit the script by clicking on script in Firebug. Debugging is simple, as it says on their official page https://getfirebug.com/javascript

Non-breaking breakpoints (trace points) in Javascript?

This is a rather complicated question that may simply be impossible with what's currently available, but if there was an easy way of doing it it would be huge.
I'm debugging some JavaScript in Chrome, and because it's very event-driven, I prefer to get trace reports of the code (what got called, etc.) instead of breakpoints. So wherever I leave a breakpoint, I'd like to see the local function name and arguments.
The closest I can get is to drop a conditional breakpoint in, like the following:
There are two big problems with this approach:
Pasting this into each breakpoint is too cumbersome. People would be far more likely to use it if it could be chosen as the default action for each breakpoint.
In Google Chrome, the log calls get fired twice.
Any ideas on a way to surmount either of these problems? I think it might be possible in IE with VS, but the UI there seems equally cumbersome.
IE11 now has "tracepoints", independent of Visual Studio. They do exactly what you asked for three years ago. I don't see them in Chrome or any other browsers yet, but hopefully they will catch on soon!
The best option I found was to edit the javascript code in Chrome's Javascript panel, adding a console.log.
It would only work after the page has been loaded (unless you can afford to put a break point after refresh and then add the logging lines) and (to be worse) you would have to do it each time you reload the page.
Good luck with your search!
I couldn't find something to do this, so I wrote my own.
Now, instead of constantly inserting and removing console.log calls, I leave the logging in and only watch it when necessary.
Warning: specific code below is untested.
var debug = TraceJS.GetLogger("debug", "mousemove");
$('div').mousemove(function(evt) {
debug(this.id, evt);
});
Every time the mouse is moved over a DIV, it generates a logevent tagged ["mousemove", {id of that element}]
The fun part is being able to selectively watch events. When you want to only see mousemove events for element #a, call the following in the console:
TraceJS('a');
When I want to see all mousemove events, you can call:
TraceJS('mousemove');
Only events that match your filter are shown. If you call TraceJS(no argument), the log calls stop being shown.

Strange JavaScript issue with timeout

I see a developer using this in my site:
window.setTimeout("pg.init()", 10);
The problem is that when I click once on the record set it works fine. However when I click on the record right away all I get is the hour glass. However if I wait and then click, it works again. What could be wrong? Any suggestions?
What happens if you invoke pg.init() without the timeout?
pg.init();
Alternatively, you could try a lower timeout, but that probably won't make any difference as it's already low:
window.setTimeout("pg.init()", 1);
Your question hardly makes any sense, but if I were to chance a guess, I would say disable the clickable element(s) (or removed the onclick handlers) within the record set once clicked, and add functionality to pg.init() which reactivates it/them.

javascript pausing consistently. How do I find what is causing it to pause?

I've got a fairly ajax heavy site and I'm trying to tune the performance.
I have a function that runs between 20 & 200 times, depending on the user.
I'm outputting the time the function takes to execute via console.time in firefox.
The function takes about 4-6ms to complete.
The strange thing is that on my larger test with 200 or runs through that function,
it runs through the first 31, then seems to pause for almost a second before completing the last 170 or so.
However, that 'pause' doesn't show up in the console.time logs, and I'm not running any other functions, and the object that gets passed to the function looks the same as all other objects that get passed in.
The function is called like this
for (var s in thisGroup.events){
showEvent(thisGroup.events[s])
}
so, I don't see how or why it would suddenly pause near the beginning. but only pause once and then continue through.
The pause ALWAYS happens on the 31st time through the function.
I've taken a close look at the 'thisGroup.events[s]' that it is being run through, and it looks like this for #31
"eventId":"5106", "sid":"68", "gid":"29", "uid":"70","type":"event", "startDate":"2010-03-22","startTime":"6:00 PM","endDate":"2010-03-22","endTime":"11:00 PM","durationLength":"5", "durationTime":"5:00", "note":"", "desc":"event"
The event immediately after the pause, #32 looks like this
"eventId":"5111", "sid":"68", "gid":"29", "uid":"71","type":"event", "startDate":"2010-03-22","startTime":"6:00 PM","endDate":"2010-03-22","endTime":"11:00 PM","durationLength":"5", "durationTime":"5:00", "note":"", "desc":"event"
another event that runs through no problem looks like this
"eventId":"5113", "sid":"68", "gid":"29", "uid":"72","type":"event", "startDate":"2010-03-22","startTime":"4:30 PM","endDate":"2010-03-22","endTime":"11:00 PM","durationLength":"6.5", "durationTime":"6:30", "note":"", "desc":"event"
From the console outputs, it doesn't appear as there is anything hanging or taking up time in the function itself, as the console.time for each event including #31,32 is 4ms.
Another strange thing here is that the total time running the for loop across the entire object is coming out as 1014ms which is right for 200 events at 4-6ms each.
Any suggestions on how to find this 'pause'?
I find it very interesting that it is consistently happening between #31 & #32 only!
------------------- a bit of a hint on the problem, but no solution -------------------
if looks like this is a lag from the where I put the html into the dom.
I've stripped out all sorts of code, but when I remove
jQuery('div#holdGroups').append(putHtml);
That is when the lag stops.
Is there any way to do a clean-up or something on the append? I've tried .html, but that isn't any better, and append is really what I want.
I can do a solid 3 count during the pause, which really isn't good, and I can't get the pause to show up anywhere in the console or profile.
It shows the actual append only taking 117ms but it is a fairly large chunk of html with 6 tables, so I don't think that is too bad.
-------------- further update - maybe garbage collection?? -----------------------
As per a few of the answers below, this may be an issue with garbage collection, though I can't be positive.
I have attempted to delete variables which are being used, such as the variable which holds the html which is added to the dom via
delete putHtml;
as well as other variables, but this has not had any affect.
if the problem is with garbage collection, maybe I'm going about cleaning it up wrong?
Is there a better way to do this?
Is there a way to determine if garbage collection is in fact the issue?
Try using console.profile() rather than console.time(). This allows you to wrap the whole block and get a more detailed breakdown of what's going on.
console.profile('my profile');
for (var s in thisGroup.events){
showEvent(thisGroup.events[s]);
}
console.profileEnd('my profile');
Does it consistently happen between #31 and #32 across different browsers? My guess is that it has something to do with the garbage collector. Also, timing in browsers is notoriously bad. I would try different browsers. If it consistently happens there, then it might be worth looking deeper into that iteration of the code. Otherwise, if it is the GC, your best bet would be to reduce the number of objects you generate.
Try collecting logs in a variable [array?] and outputing them at the end. I once did a ajax heavy "thingy" and the logs kept popping up in the console long after everything was done. The console might be the source of the lag.
Would it be possible to change the order of the data to see if that changes when the pause is? If it does, then it surely must be caused by the data. If not, then I would try narrowing down the functionality called by commenting out blocks of code until you notice the lag disappear. Experiment with that and I think you could probably find what the trouble is.
Trying loading the page with Firebug closed, therefore NOT running. I chased down a lag for three hours related to the Datepicker just the other day which went away once I closed Firebug. I was very frustrated, but not I know so any time I lag using jQuery, I close Firebug to see if it's truly something coded wrong or just Firebug getting in the way.

Categories

Resources