How do I make a div click without the mouse moving? - javascript

I'm trying to make a JavaScript code that injects into cpstest.org and when you click the start button, it automatically starts auto-clicking. I tried to make a script for it, but it just didn't work.
The start button has id start but I don't know the element to click. Viewing source code or using dev tools would be helpful, but those are blocked on my computer.
let i = 1;
document.querySelector('#start').addEventListener('click', function() {
i = 0;
});
function repeat() {
if (i == 0) {
document.querySelector(unknownId).click()};
requestAnimationFrame(repeat)
}
};
repeat();

Here's a solution:
// speed - how many CPS you want
// duration - how long the test is (in seconds)
const rapidClick = (speed, duration) => {
const startButton = document.querySelector('button#start');
const clickArea = document.querySelector('div#clickarea');
// Start the test
startButton.click()
// Click the clickArea on an interval based on the "speed" provided
const interval = setInterval(() => clickArea.click(), 1e3 / speed);
// Clear the interval after the duration has passed
setTimeout(() => clearInterval(interval), duration * 1e3);
}
// Do 100 CPS for 5 seconds
rapidClick(100, 5)
I noticed that even when setting the speed parameter to something insane like 1000 CPS, the test says only 133-139 clicks per second. Seems like it caps off at 139. Hope this helps.

Related

Automating text to speech in javascript

In JavaScript I can get the experimental text to voice working in functions that are invoked through onload or onclick.
It does not work when inside an interval timer. I guess that has something to do with setting up interrupts within an interrupt timer.
Any suggestions for how I can have a spoken message once every minute.
The test I use is
var speech = new SpeechSynthesisUtterance(“hello world”);
Window.speechSynthesis.speak(speech);
I accept this feature only works on certain browsers and devices and is experimental but is also widely used.
I am trying to have an automatic spoken status report every minute for a monitoring application
Actually, you can do this with setInterval. See the below example for one way of doing it.
var messages = ['Hello', 'world', 'It\'s me', 'Good day','How are you?','Download complete'];
var frequency = 3000;
var myInterval = setInterval(speak,frequency);
function speak() {
let rand = Math.floor(Math.random() * (messages.length-1));
console.log(rand);
let speech = new SpeechSynthesisUtterance(messages[rand]);
window.speechSynthesis.speak(speech);
}
I'm just randomly picking up words from an array, and speaking them every three seconds. You'd adapt the provided code to work as you need it to (utterance of your status every minute).
Intervals works perfectly fine with the speechSynthesis API. Here is an working example:
speech = new SpeechSynthesisUtterance("hello world");
// say "hello world" every 5 seconds
setInterval(() => window.speechSynthesis.speak(speech), 5000)
If you want to check you monitoring updates before the the "text to speach" you can build something like this:
setInterval(() => {
// Perform some calucation about the current status ...
status = getStatusUpdateAsString();
// Prepare speech
speech = new SpeechSynthesisUtterance(status);
window.speechSynthesis.speak(speech);
}, 5000)
Here is an example using the SpeechSynthesisUtterance end event, an AbortController, and setTimeout to automate a counter. You should be able to adapt it to your specific needs:
let count = 1
let controller = new AbortController()
const synth = window.speechSynthesis
const utter = new SpeechSynthesisUtterance(count)
const text = document.getElementById('text')
const onUtterEnd = () => {
setTimeout(() => {
count = count + 1
utter.text = count
text.innerHTML = `<mark>${count}</mark>`
synth.speak(utter)
}, [500])
}
const start = () => {
text.innerHTML = `<mark>${count}</mark>`
controller = new AbortController()
utter.addEventListener('end', onUtterEnd, { signal: controller.signal })
synth.speak(utter)
}
const stop = () => {
controller.abort()
synth.cancel()
}
document.getElementById('start').addEventListener('click', start)
document.getElementById('stop').addEventListener('click', stop)
<button id="start">start</button>
<button id="stop">stop</button>
<p id="text"></p>
If you're using React check out tts-react for a custom control or hook.

How to wait for x seconds before clicking the next button using Javascript

I have this code that clicks on the elements. The purpose of these buttons is to open accordions. It works but I need to modify it a little bit so as to reduce the load on the server. At the moment, all the buttons are clicked at once which causes some buttons on the same page not to work.
I was wondering if there is a way to wait for at least 3 seconds before clicking on the next button. All the buttons share the same class name.
const matchBtns = document.querySelectorAll('.classname')
matchBtns.forEach(matchbtn => matchbtn.click())
I have tried to wrap the forEach inside the setTimeout but I can't get it to work.
I tried
setTimeout(function() { matchBtns.forEach(matchbtn => matchbtn.click());}, 3000);
Thanks
You can change your implementation something like this
const matchBtns = document.querySelectorAll('.classname')
let nextClickIn = 0;
let delay = 3000;
matchbtns.forEach((matchbtn) => {
setTimeout(() => {matchbtn.click()}, nextClickIn)
nextClickIn += delay
})
Note: Provide the delay value in milliseconds
You can code this one as below:
const matchBtns = document.querySelectorAll('.classname')
let nextClick = 1;
let delay = 3000;
matchbtns.forEach((matchbtn) => {
setTimeout(() => {matchbtn.click()}, delay)
nextClick++;
delay *= nextClick
})

How to continuously check if the Date has passed in a chrome extension?

I am building a Chrome Extension and I am letting the user choose a Time when they are usually turning the PC off.
If this time has passed, I want a value to be reset back to 0 and a new Date be created.
What I did
I created a function that takes a parament of a Dare ISO String, which will then be converted into a Date Object. Inside that function I am comparing between now and the end time, and if the end time is smaller or equal to now, it means the time has passed and the value should be reset. But it's not doing anything.
I call the function inside my storage.sync.get method and inside my storage.onChanged method, so I always have the correct time to work with. But that does not seem to do it.
Here's the code:
Background.js
chrome.storage.onChanged.addListener((changes, namespace) => {
if ("reset" in changes) {
const reset = changes.reset.newValue;
console.log(reset);
checkResetTimer(reset);
}
});
chrome.storage.sync.get(["reset", "amount"], (obj) => {
const reset = obj.reset;
console.log(reset);
checkResetTimer(reset);
});
function checkResetTimer(isoTime) {
const resetDate = new Date(isoTime);
const now = new Date();
if (resetDate <= now) {
chrome.storage.sync.set({ drank: 0 }, () => {
console.log("drank has been set.");
});
}
}
The time value I get from the popup, it's an input.
I am at a loss right now. I don't know how to properly have a reset timer.
You can view my whole code in this Repository: https://github.com/Braweria/TakeAGulp
I feel the problem is, that it checks only once, but it needs to check the time consistently.
A crude approach to the problem can be the following:
Background.js
// rest of your code
const resetInterval = setInterval(() => {
chrome.storage.sync.get(["reset", "amount"], (obj) => {
const reset = obj.reset;
const resetTime = new Date(reset);
const now = new Date();
if(resetTime < now) {
// past your reset time; reset the value here
// maybe clear the interval too to stop the checking
clearInterval(resetInterval);
}
});
}, 1000 * 60); // check every minute
Essentially you have to check the value of the reset timer at a given interval to make sure whether that timer has expired.

node.js setInterval vs real time

I am working on a tool that require to measure certain amount of time (for example 2 minutes) since user interaction with a tool, this time also needs to be displayed for the user.
I started simple server loop for this reason:
setInterval(function() {
measure.time();
}, 10);
i created a code for to calculate:
this.reset = 0;
this.step = 100 // 10 ms server loop, adds 1 to reset === 100 is 1 second
this.time = function() {
if(this.reset === this.step) {
console.log('SPAWN', new Date());
this.reset = 0;
}
this.reset++;
};
this is the result of my approach:
The idea is to show clock for the user and update it every second, but it skips seconds rather often, what am i doing wrong?

setInterval pauses in Android Browser / Mobile Safari when screen times out

I've built a simple JavaScript-based timer for a mobile webapp; for the sake of example:
var a = 0;
setInterval(function() {
console.log('a', a);
a++;
}, 1000);
This runs just fine in both Mobile Safari and Android Browser. It will log to console every second and increment the value of a accordingly. (Okay, Android Browser doesn't have console.log support, but let's assume it does.)
The issue: if the screen times out (i.e. user stopped interacting with the page), the setInterval function pauses. It resumes when the user turns on their screen again. This won't work for me as I need timer to keep running.
The questions: Is there a way to prevent the setInterval function from pausing when the screen times out? If not, is it possible to prevent the screen from timing out? Any other alternatives?
Thanks in advance!
Basically, no. The phone enters a sleep state to save battery when the screen times out. Since you can't see anything anyway, a large number of processing tasks are stopped. Similar things will occur when you change tabs/windows (the page is unloaded from memory). Right now there is no way to request that the device stays on from a web application. Future support in Android for accessing hardware may provide this functionality, but personally I doubt it.
If you need always running support, you'll need to write native applications for both systems (plus on Android it can always run).
You can use the Page Visibility API to detect when the page is hidden or visible. For example, if the user navigates away from the browser and back again or the screen turns off and on.
I used this answer to help create by solution.
You will need to store the time you set your interval. Then when the visibilityChange event listener indicates the document is visible again, you can calculate the amount of time that has passed since you first started the interval and update your data as needed.
In my case I was creating a count down timer in my Angular2 project. My page was running on an iPad and the timer was pausing whenever the screen turned off. So I added the event listener in my ngOnInit(). Then when the screen turned back on I could update my timer to show the correct time left since it was started.
I am using the moment npm package to handle my date time.
The timerInfo object is a class variable that gets updated by the interval callback. self.zone.run() is used to propagate the changes to the DOM so that the updated time gets displayed.
Written in typescript:
private timerInfo:{
days?:number,
hours?:number,
minutes:number,
seconds:number
};
private startTime:Moment = moment();
private timerDuration:number = 20; // in minutes
private timerHandle:any;
ngOnInit() {
this.setVisibilityListener();
}
private setVisibilityListener():void {
var self = this;
var hidden, visibilityState, visibilityChange;
if (typeof document.hidden !== "undefined") {
hidden = "hidden";
visibilityChange = "visibilitychange";
visibilityState = "visibilityState";
}
var document_hidden = document[hidden];
document.addEventListener(visibilityChange, function () {
if (document_hidden != document[hidden]) {
if (document[hidden]) {
// Document hidden
console.log("document hidden");
} else {
// Document shown
console.log("document shown; setCountDownTimer()");
self.setCountDownTimer();
}
document_hidden = document[hidden];
}
});
}
private setCountDownTimer():void {
var self = this;
if (self.startTime) {
var startMoment = moment(self.startTime);
var endMoment = startMoment.add(self.timerDuration, "minutes");
console.log("endMoment: ", endMoment.toISOString());
self.clearTimer();
var eventTime = endMoment.unix();
var currentTime = moment().unix();
var diffTime = eventTime - currentTime;
var duration = moment.duration(diffTime * 1000, 'milliseconds');
var interval = 1000;
// if time to countdown
if (diffTime > 0) {
self.timerHandle = setInterval(() => {
self.zone.run(() => {
var diff = duration.asMilliseconds() - interval;
if (diff < 0) {
self.clearTimer();
self.timerComplete();
} else {
duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds');
self.timerInfo = {
days: moment.duration(duration).days(),
hours: moment.duration(duration).hours(),
minutes: moment.duration(duration).minutes(),
seconds: moment.duration(duration).seconds()
};
// console.log("timerInfo: ", JSON.stringify(self.timerInfo));
}
});
}, 1000);
} else {
self.timerComplete();
}
}
}
private clearTimer():void {
if (this.timerHandle) {
clearInterval(this.timerHandle);
this.timerHandle = null;
}
}

Categories

Resources