Script that goes through multiple links - javascript

I am very new to scripting macros through web browsers I am trying to figure out how to pause mid script until the page loads again. I need to go though multiple links in order to delete these junk boxes except for the first one. With the way my code is now, it will delete just one box I assume because it doesn't wait for the page to load and then go to the next link.
var cancelButtons = document.getElementsByClassName("button-ico red_ui").length;
var link;
//start at 1 to skip the first
for (i = 1; i < cancelButtons; i ++) {
link = document.getElementsByClassName("button-ico red_ui")[i].href;
// by going to this link it deletes what I want it to
// only goes through one link though, can I pause it somehow until it's ready?
window.location.href = link;
}
One way I just thought of while writing this is I could open the links in separate tabs and close them at the end and reload the page. I may explore that if there is no better option.
Thanks for looking at my post!

Related

Click event not triggering for every iteration of for loop

I want to automate this page to generate exam results. I want to generate exam results from one particular date to some other particular date. On clicking the submit button, the page generates another page in a new tab.
Manually clicking 10 times will generate 10 tabs. But see the following code:
for(let i=0;i<10;i++)
{
document.querySelector('#reg1').click();
console.log(`clicked ${i}th time`)
}
I want to trigger a click 10 times and it should generate 10 tabs accordingly. But the problem is that the click works only works on the 10th iteration and spawns 1 tab only. Help me.
see
Edit:
#Jesse
See my utility full code:
var dateFrom=new Date('2017-01')
var dateTo=new Date('2019-01')
for(var i=dateFrom;i<dateTo;i.setMonth(i.getMonth()+1))
{
// console.log(`${i.getFullYear()}-${i.getMonth()}`);
// var dd=`${i.getFullYear()}-${i.getMonth()}`;
var dd=new Date(i).toISOString().substr(0,7);
console.log(dd);
document.querySelector("input#picker.form-control").value=dd;
var type='Supplementary'
document.querySelector("select#result_type.form-control.form-email.selectoption").value=type;
document.querySelector('#reg1').click();
}
Somehow you have to execute the subsequence clicking in an asynchronous manner. I got this work by this:
let i=0;
(function doClick(){
document.querySelector('#reg1').click();
i++;
if(i<10) setTimeout(() => doClick());
})()
Another approach using async function:
(async function doClick() {
for(let i=0;i<10;i++) {
document.querySelector('#reg1').click();
await new Promise(setTimeout);
}
})()
I just figured out that my browser's popup blocker is stopping the subsequent tabs from being opened.
Try turning off your popup blocker. I was able to trigger the behavior you're after with mine off.
It works when you click it because it's a user interaction, so the blocker assumes it's something you're actively trying to do. If you trigger it programmatically, repeatedly, it gets blocked. This makes sense given that one of your browser's popup blocker's primary functions is to prevent sites from trapping you in infinite popup hell.
It's because you're using the same ID. Either switch to using a class or change the ID names so they aren't identical.

How to navigate to a dynamic appearing url in javascript

I am trying to make a small JavaScript code meant to be put in a bookmark on Google Chrome (So that it can easily be used on the console).
1) It is intended to look at a specific forum-type website I use where new posts appear dynamically on the page at a managably slow rate (1 every 5 or so minutes usually). I mainly want the script to check the page every few seconds for new posts that I haven't visited yet, and then navigate to a single unvisited post.
2) On the post's page I want it to click or otherwise activate an html button (each page will have the same button with an example id="enbut")
3) And afterwards go back to the main (static) page and wait for another post.
I am rather new to JavaScript, and I have a basic knowledge of html, but this type of thing is beyond me. (Sorry if my formatting is horrible, I'm still figuring it out)
I have come as far as:
javascript:
setInterval(function(){
window.location.href = 'http://theforum.com/new-posts';
document.getElementById('enbut').click()
}, 60000);
My main issue is recognizing and navigating to a single post on the page that I haven't visited yet, if anyone has a method to recognize unclicked/unvisited links and then navigate to them that would be the answer.
EDIT:
I have found a way to change the color of unvisited links to cyan using this code:
function addGlobalStyle(css) {
try {
var elmHead, elmStyle;
elmHead = document.getElementsByTagName('head')[0];
elmStyle = document.createElement('style');
elmStyle.type = 'text/css';
elmHead.appendChild(elmStyle);
elmStyle.innerHTML = css;
} catch (e) {
if (!document.styleSheets.length) {
document.createStyleSheet();
}
document.styleSheets[0].cssText += css;
}}
addGlobalStyle('a:visited { color: #837768 } a:link {color: #00adeb');
So now I need to find a way to navigate (in the same tab) to a link in the color #00ADEB. I am also worried with how it will decide which link to go to, since there will inevitably be situations where there is more than one unvisited link on the page.

Remaining the same state of a webpage

So I've made a web app, image below. The app has several tabs which contain different information such as graphs and indicators. The app is made using HTML & Javascript and is one document. I have implemented a Javascript timer which, every 60 seconds, loads the exact same webapp but in a different HTML document, just with different values for the graphs etc. This was just to make it easy for me as i don't have a lot of time at the moment. So every minute the web apps graphs will refresh with different data coming from a different document. So basically i have index.html, index2.html and index3.html, all with the same code/webapp but loading different values into the graphs. Heres the code for the timer:
<script type="text/javascript">
var myVar=setInterval(function(){myTimer()},60000);
$(function () {
});
function myTimer()
{
window.location.replace("index2.html");
}
</script>
The only problem with this is that when, for example, index.html reaches 60 seconds and loads index2.html it goes back to the very first tab (Summary), is there anyway to remain on the same tab even though it's loading a different document?
As #JoshuaM pointed out, the best solution would be to use AJAX, but since you seem mostly satisfied with your current method, you could use a hash on the URL to indicate which tab should be active, e.g.:
index.html#/metrics
index2.html#/metrics
etc...
(I like to put in a leading slash for this sort of thing to distinguish it from a regular anchor link or unexpectedly jumping to an element with the same ID, but in a simple case like this, index.html#metrics could work just as well).
The link for the metrics tab would look like this:
Metrics
(Keep whatever Javascript you have set up on it to make the tabs work.)
Then, when loading the next page, append the hash to it:
var nextPage = 'index2.html';
window.location = nextPage + window.location.hash;
Finally, check for the hash when first loading a page:
var hash = window.location.hash;
//hashes indicating which tab to make active should begin with a slash, e.g. #/metrics
if (hash[1]=='/') {
var currentTab = hash.substr(2);
//activate current tab...
}
Another alternative would be to use an iframe for the graph content but that would probably require more reworking of your code.

JavaScript: Reload page AFTER function has finished executing in infinite loop

I am creating a Google Chrome extension. This extension uses JavaScript to click all instances of a "follow" button on a specific web page, reloads the page, then performs the function again, in an infinite loop. It finds these follow buttons by fetching an attribute where the attribute "class" = "follow".
I am having trouble getting it to work properly, though. Instead of clicking all instances of the follow button and then refreshing, it just refreshes after one instance has been clicked.
I have tried removing the timer completely. That resulted in the script not working at all.
I removed the page refresh, and the script worked as expected, but obviously only for one instance of the page load.
Here is my code:
function tr_f() {
var followlinks = [];
for (var i=0; i < document.links.length; i++) {
if (document.links[i].getAttribute("class")=="follow"){
followlinks[followlinks.length] = document.links[i];
}
}
for (var i=0; i<followlinks.length; i++) {
var rrr=followlinks[i].onclick();
}
window.setTimeout( function(){document.location.reload();}, 5000 );
} tr_f();
There is also a button on this webpage with the "reload" class that reloads the page. Perhaps this could be implemented within the function and is only clicked once all instances of the "follow" button have been clicked, to make it work as expected. For informational purposes, we assume that the number of follow buttons on the page in question is unknown.
Any and all help regarding this will be greatly appreciated.

Can JavaScript tell the difference between leaving through the back button or a link?

My application has pages with several tabs that simply switch the visible content. However, the page also has links that will add tabs to the page. In addition, the application remembers (with cookies) which tab you last viewed in case the page is refreshed (strict cache settings cause refreshes even when using the back and forward buttons).
My problem is that the first time you visit this set of pages, it should show the first tab (Tab A). Then, you click a link, and it adds a tab, and it remembers that new tab (Tab B). However, if you hit back, now it looks like it did nothing because it remembers and displays the tab you last clicked (Tab B).
Remembering Tab B is desirable behavior if you click forward to a new page and then use our in-application history to return to the previous page. However, it is undesirable if you click the Back Button, because you want it to again show Tab A, the way it did when you first arrived.
My question is whether the JavaScript onunload event can detect the difference between leaving the page with the Back Button, or some other means. At this point, I want it to forget any tabs that it had remembered for that page.
If the difference you are trying to detect is between a user clicking a link and navigating away from the page some other way, you can detect a link click using JavaScript by attaching onclick event handlers to each link you want to observe clicks on.
So if onunload fires without an onclick first having fired, the user is leaving the page some other way than by clicking one of your tracked links.
<script type="text/javascript">
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
links[i].onclick = setGlobal;
}
function setGlobal() {
window.linkClicked = true;
}
window.onunload = function() {
if (typeof window.linkClicked === 'undefined' || !window.linkClicked) {
// they are leaving some other way than by clicking a link
}
}
</script>
It gets a bit trickier if you already have onclick events on your <a> tags, if that's the case I can provide a way to do that too.
Of course you can also attach to all the onclick events using jQuery or another JavaScript library.
Browsers remember the state of the timers (setTimeout calls) that were made on that page.
The first time the page loads the onLoad will be called, set a timer that forwards to the next page based on the history. If you are already on the last page, no problem :D, if not then it will be forwarded.
For IE the onLoad is always called, no matter if is with the back button, therefore you can put the same portion of code there.

Categories

Resources