Count the number of windows open - javascript

I am trying to count the number of Tabs that are open in my google chrome browswer with javascript. Does anyone know how to do this?
I wrote some javascript that I want repeated 10 times and then stop. Upon the completion of 1 iteration, I open a new window using:
window.open("http://www.test.com");
I want to do this 10 times than stop. Maybe there is a better way than what I am thinking...

It's a good thing that webpages are sandboxed so that other websites can't access them. If they're windows that you've opened using window.open you can save the reference you receive to the window:
var win = window.open(url);
of course you could push this to an array if you're opening a large number of windows.
var wins = [];
//looping stuff here
wins.push(window.open(url[i]);

I think the loop is just fine, but if you want to keep track,
var winList = new Array();
var count = 10;
for(var i=0; i < count; i++){
winList[i] = window.open("http://www.test.com");
}
This way, you can keep references to your windows.
hth

So I couldn't figure out a way doing what I wanted so I took a different approach. I said, lets see if google has the option in chrome to limit the number of tabs opened and I found someone wrote an extension to do exactly that. I don't know how he did but it definitely works.
Controlled multi-tab browsing

Look at the Google Chrome Extensions Developer Guide , in particular the Tabs page and the getAllInWindow function
chrome.tabs.getAllInWindow(integer windowId, function callback)
Where the callback function receives an array of tabs. Meaning you can get its length.
And if the tabs you want to keep track of are possibly in different windows, then you need to look at the Windows page and the getAll function
chrome.windows.getAll(object getInfo, function callback)
Use this to iterate over all windows and call getAllInWindow. And you're all set.

If all you want to do is open ten tabs:
var i;
for (i = 0; i < 10; i++) {
window.open("http://www.test.com");
}
But no, I don't believe you can count the number of open tabs since that could disclose information to websites that you may not want them knowing. (Do you want random websites you visit to know how many tabs you have open?)

Related

How to use JavaScript to get all element from a dynamic scroll list?

Like the title said, how do I get all elements from a scroll div? The elements in the scroll list are loaded and destroyed dynamically.
I tried to crawl all course names from this website:
https://public.enroll.wisc.edu/search?term=1204
The code below only works for one time:
let list = document.getElementsByClassName('md-virtual-repeat-scroller')[0]
let childs = document.getElementsByClassName("result__name")
console.log(childs[0].innerText)
However, if I do this, I will get the same result for 10 times:
let list = document.getElementsByClassName('md-virtual-repeat-scroller')[0]
for(let i = 0; i < 10; i++) {
let childs = document.getElementsByClassName("result__name")
for(let j = 0; j < childs.length; j++) {
console.log(childs[j].innerText)
}
// scroll by 1000px every time
list.scrollBy(0, 1000)
}
I don't know what's the problem. Is it because that scrollBy() works asynchronously? But I tried to use async and await. It still doesn't work.
Give more information in less words as a possible. Many problems could be related to browser and its version, for example. How is this script called? Are you giving commands via browser console? Have you done a copy of the site and performed some modification on it? It's hard to understand the problem in a realistic level.
Tip: Avoiding use innerText. It's slower and is supported in many browsers only for compability to scripts written to old versions of IE. (I don't know why so many examples in internet use it as first option). User textContent instead.
It's always good to test the returned value of a function/methods - specially during the development of the program.
Never ask to the StackOverFlow community (and to any other) to write progams for you!
You question "how do I get all elements from a scroll div?" is so "loose". scroll div? The answer to this, independently to the "type of div" (and tag!) would be found below.
Your code seems to be no sense in order to do what you want. Why iterate from 0 to 10?
Look at this snipet. I think it will help you
const list = document.getElementsByClassName('md-virtual-repeat-scroller')[0];// if there is no intention to reassign it. Use [0] if you are sure it's the first element of this collection
let childs = list.getElementsByClassName("result__name"); // get only elements inside the first variable!
Use the iterator of the variable.
for(item of childs)
{
/*code*/
}
I am sure you will achieve your goals!
And never suggest us (Community) to code for you or even to resolve your problem. This sound very agressive! To you too! I'm sure.
I solved my problem by reading this article:https://intoli.com/blog/scrape-infinite-scroll/
The reason why I kept getting the same elements is that scrollBy() works asynchronously, so I have to wait then evaluate the page again. I am using puppeteer by the way.
please read the article, super helpful.

How to stop a setInterval Loop in Javascript outside of code without refreshing the browser?

This may be a quite naive question but I really need some help.
Prior to writing this post, I was programming on JSBin. Turns out without me realizing, I ran a setInterval loop prompting for userInput and it kept on looping, making me unable to click anywhere to change the code to fix the loop. It kept on repeating and repeating. It got to the point where I had to refresh and lose all my hard-written-code (I was not logged in, so my code was not saved)! I want to avoid that next time.
So, my question is how do I stop any such kind of setInterval Loops, so that I am able to access my code and change it and re-run it. Below is a code that demonstrates my issue, if you try running it on JSBin.com (obviously, it is not the code I wrote before). As you can see, I can not click on my code to change it (or save it) in any way, which means I lose all my code!
This may seem like a useless question, but I really want to know ways to fix it and perhaps fixing it from the developer tools will help me be familiar with the overwhelming set of tools it has :P. So please help me if you know a solution.
Thank you for taking your time to help me! I appreciate it.
setInterval(demo,1);
function demo()
{
var name = prompt("Enter your name: ");
}
Another option is to search the developer tools "Elements" panel for the iframe (this should be doable even if the main document is unresponsive due to prompt's blocking) - then, just right click the iframe element and remove it, no need to type any Javascript. (or, if you want you can select the iframe with querySelector and remove it, eg document.querySelector('iframe').remove())
That's kind of a hack and should only be used in cases like the one exposed in OP but,
About all implementations use integers as timerid that just get incremented at every call.
So what you can do, is to clear all timeouts that were created on the page.
To do so you need to first get to which timerid we are, then call cleatTimeout or clearInterval (they do the same) in a loop until you reach the last call:
function stopAllTimers() {
const timerid = setTimeout(_=>{}); // first grab the current id
let i=0;
while(i < timerid) {
clearTimeout(i); // clear all
i++;
}
};
btn.onclick = stopAllTimers;
// some stoopid orphan intervals
setInterval(()=>console.log('5000'), 5000);
setInterval(()=>console.log('1000'), 1000);
setInterval(()=>console.log('3000'), 3000);
const recursive = () => {
console.log('recursive timeout');
setTimeout(recursive, 5000);
};
recursive();
<button id="btn">stop all timeouts</button>
Assuming the dev tools are closed, hit esc and f12 nearly simultaneously. This should open the dev tools. If it doesn't keep trying until it does.
Once they are open, hit esc and f8. Again, retry til it halts javascript execution at some arbitrary point in the code.
In the "sources" tab locate the generated script for what you wrote (offhand I don't know how it would look like from within JSBin) and literally delete the var name = prompt("Enter your name: "); line. Hitting f8 again will continue execution as if the "new" code is running. This should free you up to copy/paste your code from the site itself before you refresh the page

Opening multiple URLs with window.open

I'm pretty new to javascript, so apologies for the beginner question. Basically, I am having some problems with the window.open() method.
My code essentially takes a user string, adds a couple different variations to it, and those searches those different variations, and then is supposed to open a new window with each result. However, it seems that after my first window.open statement, the code stops executing. This is what I am working with:
var searchStrings = new Array(url1, url2, url3);
var arrayLength = searchStrings.length;
for (var i = 0; i<arrayLength; i++) {
window.open(searchStrings[i]);
}
I have tested the loop with code other than window.open to make sure it iterates through the array correctly, and I have set i to values higher than 0 to test opening the second or third item in the array.
It seems like window.open is only meant to be used once, or am I doing something else incorrectly?
Check this out: https://javascript.info/popup-windows
This documents correct usage of window.open() functionality.
Modern browsers block that kind of execution, due the risk of mis-using the functionality.
Imagine, you enter the page and 10x windows open, for no reason.
Actually, have a look you code works but chrome blocks the window and on the address bar you are notified. However Firefox blocks it completely, until manually disable the option.
windows.open can takes second parameter(name), if you want open multiple URLs you have to set unique name for each one. in your scenario you cant use this:
for (var i = 0; i < arrayLength; i++) {
window.open(searchStrings[i], '_wnd' + i);
}

How to set number of copies getPrintParams()

I am trying to add some JS to my pdf creation process to save some time. My goal is to basically click a button generate a PDF and have it print.
Right now I have:
var pp = this.getPrintParams();
pp.interactive = pp.constants.interactionLevel.full;
this.print(pp);
The only problem is that I don't know how to set the number of copies to print. I want pass a variable and print that many copies. The problem is that I can't really find any documentation discusses the methods in this class.
I know, this question is old. But I was looking for a solution, too. And I found here, that it should work with the following:
//no of copies
var n = 3;
var pp = this.getPrintParams();
//here is the magic
pp.NumCopies=eval(n);
this.print(pp);
For me, this is working with tcpdf and Adobe Reader.
Try this
var n = 3;
var pp = this.getPrintParams();
pp.NumCopies=eval(n);
this.print({bUI: false,bSilent: true,bShrinkToFit: true,printParams:pp});
Not possible, which is a good thing; since otherwise some websites would specify a high number and people who don't expect this would accidentally print lots of pages instead of just a single one.
You should call print method twice or more times, like the following:
this.print({bUI: false,bSilent: true,bShrinkToFit: true});
this.print({bUI: false,bSilent: true,bShrinkToFit: true});
I think it's not possible to set the number of copies.
See also:
Adobe's Print Production documentation

Trying to fire off a bunch of onclicks all containing a different number

There is a page I can access that contains a bunch of links like this:
<a href="#" onclick="navigate(___VIEW_RAID_2, {raid_inst_id:556816});return false;">
The number after the raid_inst_id: is always going to be different and there will be multiples on the same page all with different numbers. I'm trying to put together a javascript that will scrape the page for these links, put them in an array and then cycle through clicking them.
Ideally, an alert causing a pause between onclicks would be helpful. I've been unsuccessful so far even trying to gather the numbers and just echoing them out let alone manipulating them.
Any hints or help would be greatly appreciated!
Below is a function I tried putting together just to see if I could capture some of the onclick values for further processing but, this produces nothing...
function closeraids(){
x=document.getElementsByTagName('a');
for(i=0;i<x.length;i++)
{
attnode=x.item(i).getAttributeNode('onclick');
alert("OnClick events are: " + attnode);
}
}
Wow - 4 months later and the same problem still exists. I decided to look into this again only to find my own posted question in my Google search! Does anyone have any thoughts on what could be done here? The function I'm trying to provide will be part of a Chrome extension I already provide to users. It uses a combination of a .js file I host on my webserver and injected html content.
Any help would be appreciated!
Had some fun while making this jsfiddle: http://jsfiddle.net/Ralt/ttkGG/
Mostly because I went onto using almost fully functional style... but well. Onto your question.
I'm using getAttribute('onclick') to get the string in there. It shows something like:
"navigate(___VIEW_RAID_2, {raid_inst_id:553516});return false;"
So I just built the necessary regex to match it, and capture the number after raid_inst_id:
var re = /navigate\(___VIEW_RAID_2, {raid_inst_id:(\d+)}\);return false;/;
It's mostly rewriting the string by escaping the parentheses and putting (\d+) where you want to capture the number. (\d+ is matching a number, () is capturing the matched string.)
Using match(), I can simply get the captured string as the last element. So, rewriting the code in old IE way:
var links = document.getElementsByTagName('a'),
re = /navigate\(___VIEW_RAID_2, {raid_inst_id:(\d+)}\);return false;/;
for (var i = 0, l = links.length; i < l; i++) {
var attribute = links[i].getAttribute('onclick'),
nb;
if (nb = attribute.match(re)) {
alert(nb.pop());
}
}

Categories