Open pages with user lists and download the user ids - javascript

So I have a page which has a list of users, my total list of users is separated into 10 pages with each page showing 20 users. I want to open each page in a new window, pull the user ids on that window, close the window, and open the next page. Later I'll compile all this into a report. The problem I seem to be having is that the user_id_list only gets populated by the users on the first page so I have a bunch of duplicates.
Some of the code for parsing the pages.
full_page_string = document.getElementsByClassName("pagination")[0].outerText;
index_of_next = full_page_string.lastIndexOf("Next");
last_page_number = full_page_string.substring(index_of_next-3, index_of_next);
last_page_number.trim();
last_page_number = 2; /*DELETE LATER*/
page_array = [];
user_id_list = [];
/*Programatically create an array of pages*/
for (var page_num = 1; page_num <= last_page_number; page_num++) {
url = "example.com/users/"+ user_account_id + "/friends?page=" + page_num;
/*Open Each Page*/
var loaded_page = window.open(url, "page_" + page_num, "width=400, height=600");
page_array.push(loaded_page)
/*
For loop keps going even with settimeout. See if there is a way to delay a forloop. The thing is we need enough time to load a page, wait for it, grab users, close page, load a new page and repeat. Right now the floor loop makes it too fast.
Maybe Asyncronously open each page so they're their own instance or "thread"?
*/
loaded_page.onload = function () {
/*Find all users on the page by class*/
friends_on_page = document.getElementsByClassName("link span f5 fw7 secondary");
for (var i = 0; i <= friends_on_page.length; i++) {
pathname = friends_on_page[i].pathname;
user_id = pathname.substring(pathname.lastIndexOf("/")+1)
user_id_list.push(user_id)
console.log(user_id)
}
loaded_page.cose()
};
}

Related

Chrome Extension Top Visited List

I'm trying to make an extension that looks at your most visited sites and then tells you things about yourself given those sites.
I'm a bit lost with how to go about this and was wondering, do I run the script with the background.js file? or when they click the popup?
This is the code I'm looking to replicate,
// Event listener for clicks on links in a browser action popup.
// Open the link in a new tab of the current window.
function onAnchorClick(event) {
chrome.tabs.create({ url: event.srcElement.href });
return false;
}
// Given an array of URLs, build a DOM list of these URLs in the
// browser action popup.
function buildPopupDom(mostVisitedURLs) {
var popupDiv = document.getElementById('mostVisited_div');
var ol = popupDiv.appendChild(document.createElement('ol'));
for (var i = 0; i < mostVisitedURLs.length; i++) {
var li = ol.appendChild(document.createElement('li'));
var a = li.appendChild(document.createElement('a'));
a.href = mostVisitedURLs[i].url;
a.appendChild(document.createTextNode(mostVisitedURLs[i].title));
a.addEventListener('click', onAnchorClick);
}
}
chrome.topSites.get(buildPopupDom);
This is sort of not working at the moment.

Creating whole new view based on current user's group sharepoint 2013

I am trying to generate a view based on the current user's group name. Group Name I am gathering from the custom list.
My question is how to apply the gathered group name to 'Group Name' column as a view parameter.
The only solution I figured:
I have created a view with a parameter.
I have added an HTML Form Web Part into the same page and connected it to the list view (sending the value to the parameter via web part connection). Then with a window.onload function I gather the current user's group name and pass this value via Form Postback function. But since the Postback function triggers full page reload, it falls into the endless loop of form submission > page reload.
Another way I have tried is attaching a click event listener to the BY MY GROUPS tab and it works perfectly, but the only disadvantage is that the page reloads each time user clicks on this tab, which I would like to avoid.
So the solution that I need is a way to post the form without a page reload.
Another option suggested here is to use CSR (client side rendering), but that has its own problems:
This code does not work as it is supposed to. In the console it shows me correct items, but the view appears untouchable.
Even if it worked, the other column values are still viewable in the column filter, as in this screenshot:
So, it seems that CSR just hides items from the view (and they are still available). In other words its behavior is different from, for example, a CAML query.
Or am I getting it wrong and there's something wrong with my code?
Below you can find my CSR code:
<script type='text/javascript'>
(function() {
function listPreRender(renderCtx) {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {
var currUserID = _spPageContextInfo.userId;
var cx = new SP.ClientContext('/sites/support');
var list = cx.get_web().get_lists().getByTitle('Group Members');
var items = list.getItems(SP.CamlQuery.createAllItemsQuery());
cx.load(items, 'Include(_x006e_x50,DepID)');
cx.executeQueryAsync(
function() {
var i = items.get_count();
while (i--) {
var item = items.getItemAtIndex(i);
var userID = item.get_item('_x006e_x50').get_lookupId();
var group = item.get_item('DepID').get_lookupValue();
if (currUserID === userID) {
var rows = renderCtx.ListData.Row;
var customView = [];
var i = rows.length;
while (i--) {
var show = rows[i]['Group_x0020_Name'] === group;
if (show) {
customView.push(rows[i]);
}
}
renderCtx.ListData.Row = customView;
renderCtx.ListData.LastRow = customView.length;
console.log(JSON.stringify(renderCtx.ListData.Row));
break;
}
}
},
function() {
alert('Something went wrong. Please contact developer')
}
);
});
}
function registerListRenderer() {
var context = {};
context.Templates = {};
context.OnPreRender = listPreRender;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(context);
}
ExecuteOrDelayUntilScriptLoaded(registerListRenderer, 'clienttemplates.js');
})();
</script>

How to Cycle Through Links (sequentially) Each Page Load

I'm trying to a cycle through 5 links and want to cycle through them on each page load (i.e. first visitor page load shows link 1, second visitor page load shows link 2, etc. then back to link 1 after link 5 shows)
I found this code below which does cycle through the links randomly, but I'm trying to get them to load in order. Is this possible? Thanks in advance for your help.
<li id="RotateLink"></li>
<script language="javascript">
var links = new Array("link1", "link2", "link3", "link4", "link5");
var randomnumber=Math.floor(Math.random()*5)
document.getElementById("RotateLink").innerHTML = links[randomnumber];
</script>
(also, some tips on changing "link1" to an actual link would be helpful too)
Since you lose your JS context on page load, you could make use of the browser's inbuilt localStorage api (https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage).
<li id="RotateLink"></li>
<script language="javascript">
var links = new Array("link1", "link2", "link3", "link4", "link5");
var numberFromStorage = localStorage.getItem("cycle-link-number") || "0"; // zero if getItem returns null
var number = parseInt(numberFromStorage); //cast to number since storage saves strings
number = number >= links.length ? 0 : number; // reset if reached max
localStorage.setItem("cycle-link-number", number + 1); //set item for next iteration
document.getElementById("RotateLink").innerHTML = links[number];
</script>
To create your link you could do something like this:
// instead of
// document.getElementById("RotateLink").innerHTML = links[number];
// do
var link = document.createElement("a"); // creates anchor element
link.href = 'someUrl'; // sets the url, e.g link.href = 'http://www.google.de';
link.innerHTML = 'linktext'; // set the link text
document.getElementById("RotateLink").appendChild(link); // appends the link to the element with the id "RotateLink"
As you need to know the link that was previously loaded after page reload, You need to store that information somewhere so that you can use it on the next reload. We have browser local storage to do that. You can store the index of the link that was previously loaded and increment the link based on that. More details about HTML5 Web Storage here here
<li id="RotateLink"></li>
<script language="javascript">
var links = new Array("link1", "link2", "link3", "link4", "link5");
var currentIndex=localStorage.currentIndex;
if(currentIndex){
if(currentIndex < links.length-1)
currentIndex = parseInt(currentIndex)+1;
else
currentIndex = 0;
} else {
currentIndex = 0;
localStorage.setItem('currentIndex', currentIndex);
}
localStorage.currentIndex = currentIndex;
document.getElementById("RotateLink").innerHTML = links[currentIndex];
</script>

Javascript Tabs with HTML 5 and CSS3 not working

Hello I am trying to create HTML form with JavaScript tabs. There are three tabs and I want to hide second and third tab contents in page on load.
This is my Javascript function
window.onload = function() {
// get tab container
var container = document.getElementById("tabContainer");
var tabcon = document.getElementById("tabscontent");
//alert(tabcon.childNodes.item(1));
// set current tab
var navitem = document.getElementById("tabHeader_1");
//store which tab we are on
var ident = navitem.id.split("_")[1];
//alert(ident);
navitem.parentNode.setAttribute("data-current",ident);
//set current tab with class of activetabheader
navitem.setAttribute("class","tabActiveHeader");
//hide two tab contents we don't need
var pages = tabcon.getElementsByTagName("div");
for (var i = 1; i < pages.length; i++) {
pages.item(i).style.display="none";
};
//this adds click event to tabs
var tabs = container.getElementsByTagName("li");
for (var i = 0; i < tabs.length; i++) {
tabs[i].onclick=displayPage;
}
}
When I run these file in localhost it is working correctly. But I wants to run this file in my server. When I store this file in my server, it is not working. It show all tab contents and not hide second and third tab contents in page load as shown in figure.
Tabs Image
I cant identify the reason. Any help is greatly appreciated.

JS cookies refresh itself when the page refreshes

I need to use cookies for my new webshop, so if the page refreshes the old values will stay in.
Now i've created my cookies, and it works perfectly fine, but when I'm refreshing the page, the cookie goes empty again. If i'm going to a different page, the cookie stays (path:/)
Now i'm confused and need someone to clarify what i'm doing wrong right here, so I came here to ask my question!
Here is the code im using
$.cookie.raw = true;
$.cookie.json = true;
$.cookie('cart', unescape);
function UpdateTotals() {
TotalPrice = 0;
for (var i = 0; i < Orders.length ; i++) {
var SearchResult = SubMenuItems.filter(function(v) {
return v.submenu_id === Orders[i];
})[0];
TotalPrice += parseFloat(SearchResult.price);
$.cookie('cart', JSON.stringify(Orders), { expires: 7, path: '/' });
Now if I click on some orders, the cookies stays filled with the jSon values.

Categories

Resources