phantomjs : Go till the end of dynamically loaded Facebook page - javascript

I wrote a javascript which when used in browser such as chrome, keeps on scrolling such facebook pages in which more content is loaded as you scroll.
i = 0;
minutes = 30;
counter = minutes * 60;
function repeatScroll()
{
console.log('scrolling');
if (i < counter)
{
window.scrollTo(0, document.body.scrollHeight);
i++;
}
setTimeout(repeatScroll, 5000);
}
repeatScroll();
I wanted to do same using phantomjs, but I am unable to do so. I am doubting it has something to do with the delay, but I am unable to figure it out.
This is a snippet from my phantom js code :
var url = "https://www.facebook.com/search/965993006761563/likers";
page.open(url, function (status) {
setTimeout(function () {
page.evaluate(function () {
console.log('gooooooooooooooooo');
});
page.render("liker.png");
page.evaluate(function() {
i = 0;
minutes = 30;
counter = minutes * 60;
function repeatScroll()
{
console.log('scrolling');
if (i < counter)
{
window.scrollTo(0, document.body.scrollHeight);
i++;
}
setTimeout(repeatScroll, 5000);
}
repeatScroll();
});
Console only outputs scrolling once. I am not sure what changes do I need to do.
After scrolling all the way through out I want to extract all profile id's too. Planning to add this just below the above code.
var title = page.evaluate(function() {
var e=document.getElementsByClassName("fsl fwb fcb");
var ids = [];
for(var i = 0 ; i < e.length; i++)
{
ids.push(JSON.parse(e[i].childNodes[0].getAttribute("data-gt")).engagement.eng_tid);
}
console.log(ids);
return ids;
});
Also, when I currently add it, I do not get any profile id output.
Edit : I already read this (How to scroll down with Phantomjs to load dynamic content) but this is not present in my case.

Related

getJSON issue with loading images across Safari and iOS

I'm trying to load a series of images that disappear at an interval of 300ms on page load.
The images are chosen at random from a JSON file, based on the users screen dimensions.
This works in Chrome but seems to fail randomly, and does not work at all in Safari (pauses on a random image) or on iOS (fails to load any images at all).
Here is my code:
// get the screen orientation based on css media query
var orientation = window.getComputedStyle(document.querySelector('body'), ':after').getPropertyValue('content').replace(/['"]+/g, '');
window.slides = [];
// function to randomise the order of an array
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
$(document).ready(function() {
$( 'html' ).addClass( 'js' ).removeClass( 'no-js' );
// define the category and number of slides
var imageDirs = { "lovers": 16 };
// get slide urls from json file
$.getJSON('slides/slides.json', function (data) {
for (var thisDir in imageDirs) {
var theseSlides = [];
theseSlides = data[thisDir][orientation];
shuffle(theseSlides)
slides = theseSlides.slice(0, imageDirs[thisDir]);
}
})
.done(function() {
// randomise order of slides
shuffle(slides);
// have one blank slide at the beginning of the animation
slides.push("initial-slide.png");
if ( slides.length ) {
for (var i = 0; i < slides.length; i++) {
$('#wrapper').append('<img class="slide" src="slides/' + slides[i] + '">');
}
}
});
});
$(window).on('load', function(){
// wait for images to load before displaying animation
$('#wrapper').waitForImages(true).done(function() {
$('#preloader').remove();
var currentSlides = [];
$('.slide').each(function(){
currentSlides.push($(this));
});
// remove slides at an interval of 300ms
var timer = setInterval(function(){
if (currentSlides.length){
currentSlides.pop().remove();
} else {
clearInterval(timer);
}
}, 300);
});
});
JSFiddle: https://jsfiddle.net/robertirish/6g41vwnL/59/
Live site: http://robertirish.com
Thanks in advance!
Thanks for the fiddle. Basically your problem is that in your load event the images haven't been appended to be the DOM yet. You can see this by logging currentSlides: https://jsfiddle.net/1fb3gczq/
So, you need to ensure the DOM is ready before you manipulate it. I've moved your function to the ajax success which works in this case, but on slower connections you'll want to only run the effect once all the images have loaded in the DOM. Here's a working fiddle: https://jsfiddle.net/rcx3w48b/

How to unsubscribe from all the Youtube channels at once?

I have subscribed to more than 300 Youtube channels in past 10 years, and now I have to clean my Youtube, unsubscribing all one by one will take some time, is there a way to unsubscribe all the cannels at once?
Step 1: Go to https://www.youtube.com/feed/channels and scroll to the bottom of the page to populate all items to the screen.
Step 2: Right-click anywhere on the page and click "Inspect Element" (or just "Inspect"), then click "Console", then copy–paste the below script, then hit return.
Step 3:
var i = 0;
var myVar = setInterval(myTimer, 3000);
function myTimer () {
var els = document.getElementById("grid-container").getElementsByClassName("ytd-expanded-shelf-contents-renderer");
if (i < els.length) {
els[i].querySelector("[aria-label^='Unsubscribe from']").click();
setTimeout(function () {
var unSubBtn = document.getElementById("confirm-button").click();
}, 2000);
setTimeout(function () {
els[i].parentNode.removeChild(els[i]);
}, 2000);
}
i++;
console.log(i + " unsubscribed by YOGIE");
console.log(els.length + " remaining");
}
Step 4: Sit back and watch the magic!
Enjoy!!
NOTE: If the script stops somewhere, please refresh the page and follow all four steps again.
Updating the answer provided by everyone else (as the latest update did not work for me):
var i = 0;
var count = document.querySelectorAll("ytd-channel-renderer:not(.ytd-item-section-renderer)").length;
myTimer();
function myTimer () {
if (count == 0) return;
el = document.querySelector('.ytd-subscribe-button-renderer');
el.click();
setTimeout(function () {
var unSubBtn = document.getElementById("confirm-button").click();
i++;
count--;
console.log(i + " unsubscribed");
console.log(count + " remaining");
setTimeout(function () {
el = document.querySelector("ytd-channel-renderer");
el.parentNode.removeChild(el);
myTimer();
}, 250);
}, 250);
}
For me this did the trick.
Youtube Channel Unsubscriber (Works April-2020)
Access the link : https://www.youtube.com/feed/channels
Press F12
Insert the code below in your console
function youtubeUnsubscriber() {
var count = document.querySelectorAll("ytd-channel-renderer:not(.ytd-item-section-renderer)").length;
var randomDelay = 500;
if(count == 0) return false;
function unsubscribeVisible(randomDelay) {
if (count == 0) {
window.scrollTo(0,document.body.scrollHeight);
setTimeout(function() {
youtubeUnsubscriber();
}, 10000)
}
unsubscribeButton = document.querySelector('.ytd-subscribe-button-renderer');
unsubscribeButton.click();
setTimeout(function () {
document.getElementById("confirm-button").click()
count--;
console.log("Remaining: ", count);
setTimeout(function () {
unsubscribedElement = document.querySelector("ytd-channel-renderer");
unsubscribedElement.parentNode.removeChild(unsubscribedElement);
unsubscribeVisible(randomDelay)
}, randomDelay);
}, randomDelay);
}
unsubscribeVisible(randomDelay);
}
youtubeUnsubscriber();
References
https://github.com/vinnyfs89/youtube-unsubscriber
This is a little addition to the best answer:
You can also use jscompress[dot]com to compress the script, then add javascript: at the beginning of the script, and add it to your bookmarks — you can run it from there — just in case you're not comfortable using console or something like that.
Most effective values:
(copy all above this, including the last)
var i = 0;
var myVar = setInterval(myTimer, 200);
function myTimer () {
var els = document.getElementById("grid-container").getElementsByClassName("ytd-expanded-shelf-contents-renderer");
if (i < els.length) {
els[i].querySelector('[aria-label="Unsubscribe from this channel."]').click();
setTimeout(function () {
var unSubBtn = document.getElementById("confirm-button").click();
}, 500);
setTimeout(function () {
els[i].parentNode.removeChild(els[i]);
}, 1000);
}
i++;
console.log(i + " unsubscribed by YOGIE");
console.log(els.length + " remaining");
}
Updating MordorSlave answer. Just did it a moment ago.
Go to https://www.youtube.com/feed/channels and copy/paste the following in the console:
var i = 0;
var myVar = setInterval(myTimer, 200);
function myTimer() {
var els = document.getElementById("contents").getElementsByClassName("ytd-subscribe-button-renderer");
if (i < els.length) {
els[i].querySelector('.ytd-subscribe-button-renderer').click();
setTimeout(function() {
var unSubBtn = document.getElementById("confirm-button").click();
}, 500);
setTimeout(function() {
els[i].parentNode.removeChild(els[i]);
}, 1000);
}
i++;
console.log(i + " unsubscribed");
console.log(els.length + " remaining");
}
https://gist.github.com/itsazzad/c1d86c5db86258ca129554a7b9ed92a7
Use the DELAY const wisely; consider your net speed.
// Go to the following link in your YouTube: https://www.youtube.com/feed/channels
// Scroll the page all the way down until you reach the very last subscribed channel in your list
const DELAY = 100;
const delay = ms => new Promise(res => setTimeout(res, ms));
const list = document.querySelectorAll("#grid-container > ytd-channel-renderer");
for (const sub of list) {
await delay(DELAY);
sub.querySelector("#subscribe-button > ytd-subscribe-button-renderer > paper-button").click();
await delay(DELAY);
document.querySelector("#confirm-button > a").addEventListener('click', async event => {
await delay(DELAY);
console.log(sub.querySelector("#text").innerText);
await delay(DELAY);
});
await delay(DELAY);
document.querySelector("#confirm-button > a").click()
await delay(DELAY);
}
Go to https://www.youtube.com/feed/channels.
Scroll all the way down till you see the last subscribed channel.
Open the javascript console, paste the following code and hit enter
let btns = document.querySelectorAll('paper-button > yt-formatted-string');
for (let i = 0; i < btns.length; i += 1) {
if (btns[i].innerText.toLowerCase() === 'subscribed') {
btns[i].click();
document.getElementById('confirm-button').click();
}
}
Note: For me this method worked on Firefox. Chrome was giving warnings and the page became unresponsive. Worked on Oct 20th 2020 for an account with 956 subscribed channels.
Hmm, wish I'd googled before rolling out my own. I had some fun with async and await with this. The screen does some ugly flashing while it's trying to unsubscribe stuff, but this does the job pretty well.
One prerequisite for this script to catch all channels in one go is to "exhaust" the scroller in the page ie., keep scrolling until you reach the end of your channel list. As others have stated, head on over to YouTube Channels, open the developer console and paste the script that follows.
I've commented in relevant parts, in case this ends up becoming a learning experience for someone ;)
/**
* Youtube bulk unsubsribe fn.
* Wrapping this in an IIFE for browser compatibility.
*/
(async function iife() {
// This is the time delay after which the "unsubscribe" button is "clicked"; Tweak to your liking!
var UNSUBSCRIBE_DELAY_TIME = 2000
/**
* Delay runner. Wraps `setTimeout` so it can be `await`ed on.
* #param {Function} fn
* #param {number} delay
*/
var runAfterDelay = (fn, delay) => new Promise((resolve, reject) => {
setTimeout(() => {
fn()
resolve()
}, delay)
})
// Get the channel list; this can be considered a row in the page.
var channels = Array.from(document.getElementsByTagName(`ytd-channel-renderer`))
console.log(`${channels.length} channels found.`)
var ctr = 0
for (const channel of channels) {
// Get the subsribe button and trigger a "click"
channel.querySelector(`[aria-label^='Unsubscribe from']`).click()
await runAfterDelay(() => {
// Get the dialog container...
document.getElementsByTagName(`yt-confirm-dialog-renderer`)[0]
// and find the confirm button...
.querySelector(`#confirm-button`)
// and "trigger" the click!
.click()
console.log(`Unsubsribed ${ctr + 1}/${channels.length}`)
ctr++
}, UNSUBSCRIBE_DELAY_TIME)
}
})()
If someone is looking for a working solution, the following script worked for me:
Go to https://www.youtube.com/subscription_manager and run
$$('.yt-uix-button-subscribed-branded').forEach(function(el) { el.click(); $$('.overlay-confirmation-unsubscribe-button').forEach(function(el) { el.click(); }); console.log('Bye YouTube'); });
Ref: https://www.reddit.com/r/youtube/comments/ad3jv5/mass_unsubscribe_script/
My solution, most up to date i think, but things always changing...
var unsubBtns = document.querySelectorAll(' div:nth-child(2) > div:nth-child(2) > div:nth-child(2) > ytd-subscribe-button-renderer:nth-child(1) > paper-button:nth-child(1)');
var i = 0;
var interV = setInterval(function(){
unsubBtns[i].click();
i++;
document.querySelector('yt-formatted-string.style-blue-text').click()
}, 1000);
Extending on Jani's answer, this one has a DOM progress counter. Absolutely no jQuery.
(function() {
var i = 0;
var ytdElem = document.querySelector("ytd-page-manager ytd-browse.ytd-page-manager");
ytdElem.innerHTML = '<div style="font: 11pt arial; background: yellow; color: white" id="ytdjsds"></div>' + ytdElem.innerHTML;
var element = document.getElementById("ytdjsds");
var count = document.querySelectorAll("ytd-channel-renderer:not(.ytd-item-section-renderer)").length;
if (count == 0) {
element.innerHTML = "No subscriptions were found on your account.";
return;
}
element.innerHTML = `Deleting subscription 1 of ${count}`;
function myTimer() {
if (count == 0) {
element.innerHTML = `Successfully deleted subscriptions`;
return;
}
element.innerHTML = `Deleting subscription ${i + 1} of ${count}`;
el = document.querySelector('.ytd-subscribe-button-renderer');
el.click();
document.getElementById("confirm-button").style.display = "none";
setTimeout(function() {
var unSubBtn = document.getElementById("confirm-button").click();
i++;
setTimeout(function() {
el = document.querySelector("ytd-channel-renderer");
el.parentNode.removeChild(el);
myTimer();
}, 250);
}, 250);
}
myTimer();
})();
as of October 2021
from this page https://www.youtube.com/feed/channels
var list = $$('yt-formatted-string.ytd-subscribe-button-renderer')
function foo($$) {
if (list.length === 0) return
var el = list.pop()
el.click()
setTimeout(_=>{
var cancel = $$('yt-formatted-string.yt-button-renderer')[1]
cancel.click()
console.log('done')
setTimeout(_=>{foo($$)},100)
}, 100)
}
foo($$)

Change img src every second using Jquery and Javascript

I have been trying to write a script that changes an image src every two seconds based on a list.
So, everything is inside a forloop that loops over that list:
$(document).ready(function() {
var lis = {{dias|safe}}; <----- a long list from django. This part of the code works fine.
for (i=0; i<lis.length; i++){
src_img = lis[i][1];
var timeout = setInterval(function(){
console.log(src_img)
$("#imagen").attr("src", src_img);
}, 2000)
}
});
It doesn't work, the console logs thousands of srcs that correspond to the last item on the list. Thanks a lot for your help.
you don't need to run cycle in this case, you just save "pointer" - curentImage and call next array item through function ever 2 sec
var curentImage = 0;
function getNextImg(){
var url = lis[curentImage];
if(lis[curentImage]){
curentImage++;
} else {
curentImage = 0;
}
return url;
}
var timeout = setInterval(function(){
$("#imagen").attr("src", getNextImg());
}, 2000)
var curentImage = 0;
var length = lis.length;
function NewImage(){
var url = lis[curentImage];
if(curentImage < length){
currentImage++;
}
else{
currentImage = 0;
}
return url;
}
var timeout = setInterval(function(){
$("#imagen").attr("src", getNextImg());
}, 2000)
PS: Better than the previous one, Checks for lis length and starts from first if you reach end.
You need something like this
$(document).ready(function() {
var index = 0;
setInterval(function(){
src_img = lis[index++ % lis.lenght][1]; // avoid arrayOutOfBounds
$("#imagen").attr("src", src_img);
}, 2000)
});

reloading url from an array in javascript

I am working on the following code for a chrome extension. Basically I want it to check the page that initially loads and if it matches my website st.mywebsite.com it will execute the code. Right now it doesn't check and will execute any pages that loads. I am trying to get it to load http://st.mywebsite.com/?q= plus the terms in the array. So every X number of seconds/minutes it will load a new term in the array and add it to the url http://st.mywebsite.com/?q=can anyone help?
if((window.location.hostname != "st.mywebsite.com")){
window.onload = function() {
terms = new Array("5d65sd", "95sd4s", "h2j4g8h", "c87e2dd", "e6e5f2g4", "3m5g5gv");
min = 1;//minimum
max = 60;//maximum
randomnumber = Math.floor(Math.random() * (max - min + 1)) + min;
var seconds = randomnumber;
var timer;
function countdown() {
var container = document.getElementById('right');
seconds--;
if(seconds > 0) {
container.innerHTML = '<p>Please wait <b>'+seconds+'</b> seconds.</p>';
} else {
window.location = 'http://st.mywebsite.com/?q='+terms;
}
}
timer = setInterval(countdown, 1000);
}
}
At the line you have window.location, change it to window.location.href

Can i create a javascript carousel which contains a flash file as well as static images?

I was wondering if it's possible to include an swf within a javascript carousel that currently just contains stagic images. What I'm looking to do is include a flash animation within the carousel.
I guess I've got two main questions:
Is it possible to cycle through flash files in the same way as an image?
How would I get the javascript and flash to interact so the flash file would know when it had been selected?
If it helps, here's the js we're using:
$(document).ready(function(){
var $looper = true;
var timer;
var currentSlide = 0;
var cell = 0;
var row = 1;
var hCycles = 0;
var aCycles = 0;
//no. of full cycles
var homecycles = 2;
var aboutcycles = 2;
//aboutSlide speed
var fast = 1200;
var slow = 4000;
//hide homepage slides
$('#slide2').fadeOut(0);
$('#slide3').fadeOut(0);
$('#slide4').fadeOut(0);
$('#slide5').fadeOut(0);
$('#slide6').fadeOut(0);
//hide about slides
$('.a-slide1').fadeOut(0);
$('.a-slide2').fadeOut(0);
$('.a-slide3').fadeOut(0);
$('.a-slide4').fadeOut(0);
$('#slide-c1 .a-slide1').fadeIn(1200);
runSlide(fast);
function runSlide(x) {
if ($('body').is('.about')) {
setTimeout(function() {
aboutSlides();
}, x);
} else {
if ($looper) {
setTimeout(function() {
slideShow();
}, 4000);
}
}
}
function slideShow() {
if ($looper) {
if (currentSlide++ < 6 && hCycles < homecycles) {
$('#slide'+ currentSlide).fadeOut(1200);
if (currentSlide == 6) {
$('#slide1').fadeIn(1200);
$('#slide-wrapper li').removeClass('active');
$('#btn1').addClass('active');
currentSlide = 0;
hCycles = hCycles+1;
} else {
$('#slide'+ (currentSlide+1)).fadeIn(1200);
$('#slide-wrapper li').removeClass('active');
$('#btn'+ (currentSlide+1)).addClass('active');
}
runSlide();
} else {
$looper = false;
}
}
};
$('#slide-wrapper li').each(function(index) {
$('#btn'+(index+1)).click(function(){
$looper = false;
$('.slide').fadeOut(1200);
$('#slide'+ (index+1)).fadeIn(1200);
$('#slide-wrapper li').removeClass('active');
$(this).addClass('active');
});
});
function aboutSlides() {
if (cell++ < 3 && aCycles < aboutcycles) {
if (cell == 3) {
if (row < 3) {
row = row+1;
} else {
row = 1;
aCycles = aCycles+1;
}
var hide = (row-1);
if ((row-1) == 0) {hide = 3}
$('#slide-c1 .a-slide'+ hide).fadeOut(1200);
$('#slide-c1 .a-slide'+row).fadeIn(1200);
cell = 0;
runSlide(fast);
} else {
$('#slide-c'+(cell+1)+' .a-slide'+ (row-1)).fadeOut(1200);
$('#slide-c'+(cell+1)+' .a-slide'+(row)).fadeIn(1200);
if (cell == 2) {
runSlide(slow);
} else {
runSlide(fast);
}
}
} else {
// create the final strip
$('#slide-c3 .a-slide3').fadeOut(1200);
$('#slide-c3 .a-slide4').fadeIn(1200);
}
}
});
Thanks!
There isn't any problem as to whatever content you want to put in your slides. As long as it is valid html, it's valid in a slide. Countless jquery/motools/etc plugins let you specify whatever you want for content.
flash is valid.
But you might want to revert to another revealing method. setting the opacity on a swf from javascript is complex and yields to different results, according to browser and flash version. If your flash file is custom made, then you can create a function that fades it to white for example, and call it from javascript. But from experience, changing the opacity of a swf is calling for trouble.
I don't know if this is relevant enough to be an answer, I wanted to post it as a comment, but there isn't any comment button. Oh well.

Categories

Resources