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.
Related
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.
I'm installing a FB event tracking pixel to load when a button is clicked on this page: https://www.naiik.com/booking/
I found this earlier post, but the event is not loading for me: Add FB pixel event code into button - Squarespace
I've specifically injected this code:
<script>
(function() {
var btns = document.getElementsByClassName("sqs-block-button-element");
btns.addEventListener("click", function() {
fbq("track", "Lead");
});
})();
</script>
I injected it in the page specific header.
I'm using Facebook's Pixel Helper chrome extension and it keeps saying that this pixel has not loaded. All the while, the main FB pixel, which I installed previously, is working just fine.
Thank you!
There are 2 errors in your code.
1. Invalid setEventListener() method usage
When you call document.getElementsByClassName('class') the resulting value is a special HTMLCollection array of all elements with a given class that were found in the DOM. (Notice the plural spelling of the function name — elements.)
What to do next:
To achieve the desired result you can change your code to enumerate over the list of results returned by .getElementsByClassName; to do that, use a simple for loop on your result.
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
fbq("track", "Lead");
});
}
2. Incorrect selector for Squarespace button classes
If you will call the selector and inspect the resulting HTMLCollection array or directly inspect the buttons on the page you will see that button blocks that Squarespace uses have the class .sqs-block-button-element. It makes sense: after all these are Button Blocks you have placed in your page editor. The Form Block, on the other hand, does not register it's Submit button with that class (it's a .button.sqs-system-button.sqs-editable-button).
What to do next:
To achieve correct Facebook Pixel installation you need to register it on the meaningful marketing event emitters. Unfortunately, there is no one commonly used class for the majority of Squarespace buttons.
You could keep it simple and just register the Form Block .button in your addEventListener code. This would have an unfortunate consequence of not catching clicks to other buttons.
You also could target both the Button Block and Form Block Buttons, add them to a single Array object and then attach a listener to each one of them.
But there is a better option.
Use the necessity of targeting different types of buttons to indicate different Pixel properties.
E.g. the Form Block button will generate a Form-specific Pixel event, Button block — Button-specific Pixel event:
Example:
var blockBtns = document.getElementsByClassName("sqs-block-button-element");
var formBtns = document.getElementsByClassName("button");
Your new code:
<script>
(function() {
var blockBtns = document.getElementsByClassName("sqs-block-button-element");
var formBtns = document.getElementsByClassName("button");
for (var i = 0; i < blockBtns.length; i++) blockBtns[i].addEventListener("click", function() {
fbq("track", "Lead", {
eventSource: "Button Block"
});
});
for (var i = 0; i < formBtns.length; i++) formBtns[i].addEventListener("click", function() {
fbq("track", "Lead", {
eventSource: "Form Block"
});
});
})();
</script>
You can refactor it as you wish and/or use the Squarespace-native YUI library to improve and stabilize the code.
Additional recommendations:
Most likely the Pixel Extension error is due to your AdBlock extension. You must disable AdBlock on your domain and on your .squarespace.com internal subdomain to develop with Pixel and other marketing tools.
If you initialize your pixel with advanced customer matching — the em variable in your Pixel init() call — you need to correctly pass the customer data. That's a very powerful marketing technique and you should research what's possible with Squarespace (not easy).
Use fbq('track', 'PageView'); to track visitors coming to your lead-generating pages. Not every user clicks a button to call or submit a form, but every user that chooses to view a "Subscription" or "Contact" page is a prospective customer.
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!
Ok this thing is driving me crazy. I have a simple project in which I use this mobile bootstrap theme and this text-to-speech library
Whenever there's an error in my function, the page just refreshes itself. In this way I can never read any output from the console.
Here's my code:
<script>
$(document).ready(function() {
$('#input-submit').click(function() {
var text = $('#input-box').val();
console.log(text);
for (var i = 0;i < text.length; i++){
alert('test');
meSpeak.speak(text.charAt(i));
}
});
});
</script>
I want my app to spell out loud whatever the user fills in. The function works correctly until the meSpeak.speak(text.charAt(i)); line. When I type in a 3 character word I get 3 alerts, and then the page just refreshes itself.
Why does it refresh when there's something not working? I want to read the output from the console without using alerts. Also, does anyone know why I can't use meSpeak.speak(text.charAt(i)); like this?
You're not preventing the submit button from "submitting" the page, and as you've most likely set no destination, it's submitting to the same location, causing a page refresh.
Preventing the click event can be done in jQuery by returning false at the end of the function
$('#input-submit').click(function () {
/* etc */
return false;
});
Demo to play with
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.