Get the document object of an IFrame in PhantomJS? - javascript

I am trying to get the document of an Iframe after setting the iframe.src.
I am calling this in phantom-node.
The function returns an error when the iframe is empty:
fetchGuestbookEntries: function () {
var getGuestbookForPage = function (doc) {
var result = [];
var rows = doc.querySelectorAll('td[class="guestbook"]');
var date = "";
var entry = "";
for (var i = 0; i < rows.length; i++) {
date = i % 2 == 0 ? rows[i].innerText : date;
entry = i % 2 != 0 ? rows[i].innerText : entry;
if (date && entry) {
var info = date.split('\n').map(function (elem) {
return elem.replace('\n', '').trim();
});
result.push(
{
info: {
guestname: info[0],
date: new Date(info[3]).toISOString().slice(0, 10),
time: info[4].replace(/Uhr|h/gi, '').trim()
},
entry: entry.trim()
}
);
date = "";
entry = "";
}
}
return result;
};
var getPaginationSize = function () {
return document.querySelector('td[class="guestbook_navijump"]') ?
document.querySelector('td[class="guestbook_navijump"]').querySelectorAll('a').length : 0;
};
var getIframeDoc = function(ifrm) {
return ifrm.document ||
ifrm.contentDocument ||
ifrm.contentWindow.document;
};
var pagination = getPaginationSize();
var entries = [];
for (var i = 0; i <= pagination; i++) {
var paginationPageUrl = window.location.href + "?jump=" + i;
var iframe = document.createElement('iframe');
iframe.src = paginationPageUrl;
var doc = getIframeDoc(iframe);
entries.push(getGuestbookForPage(doc));
}
return entries;
}
Is there a way to get the document?
The error:
Uncaught TypeError: Cannot read property 'document' of null
at <anonymous>:2:21
at Object.InjectedScript._evaluateOn (<anonymous>:895:140)
at Object.InjectedScript._evaluateAndWrap (<anonymous>:828:34)
at Object.InjectedScript.evaluate (<anonymous>:694:21)
I normally open the Page in PhantomJS.

You should be able to get it with this
document.getElementById('myframe').contentWindow.document

Related

How to handle Cannot read properties of undefined (reading '0') error?

How to handle Cannot read properties of undefined (reading '0'). I want to trigger this in ajax success of select onchange.
var date_sched = [];
const output = {
[date_sched[0].user_id]: date_sched[0].dates,
};
//var doctor_dates;
$("#schedDay").on("show.datetimepicker update.datetimepicker",
function() {
highlight();
});
function highlight() {
// var dateToHilight = text;
var dateToHilight = output;
var array = $("#schedDay").find(".day").toArray();
for (var i = 0; i < array.length; i++) {
var date = array[i].getAttribute("data-day");
if (dateToHilight[doctor_dates].indexOf(date) > -1) {
array[i].classList.add('highlighted');
}
}
}

Linkedin Autoconnect With User role

I am trying to fix this script to automatically connect people you may know on Linkedin based on User roles (CEO e.t.c), Can someone help me fix this, Below is my code; I have tried the script on almost all browsers, Somebody help fix this.
var userRole = [
"CEO",
"CIO"
];
var inviter = {} || inviter;
inviter.userList = [];
inviter.className = 'button-secondary-small';
inviter.refresh = function () {
window.scrollTo(0, document.body.scrollHeight);
window.scrollTo(document.body.scrollHeight, 0);
window.scrollTo(0, document.body.scrollHeight);
};
inviter.initiate = function()
{
inviter.refresh();
var connectBtns = $(".button-secondary-small:visible");
//
if (connectBtns == null) {var connectBtns = inviter.initiate();}
return connectBtns;
};
inviter.invite = function () {
var connectBtns = inviter.initiate();
var buttonLength = connectBtns.length;
for (var i = 0; i < buttonLength; i++) {
if (connectBtns != null && connectBtns[i] != null) {inviter.handleRepeat(connectBtns[i]);}
//if there is a connect button and there is at least one that has not been pushed, repeat
if (i == buttonLength - 1) {
console.log("done: " + i);
inviter.refresh();
}
}
};
inviter.handleRepeat = function(button)
{
var nameValue = button.children[1].textContent
var name = nameValue.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
function hasRole(role){
for(var i = 0; i < role.length; i++) {
// cannot read children of undefined
var position = button.parentNode.parentNode.children[1].children[1].children[0].children[3].textContent;
var formatedPosition = position.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var hasRole = formatedPosition.indexOf(role[i]) == -1 ? false : true;
console.log('Has role: ' + role[i] + ' -> ' + hasRole);
if (hasRole) {
return hasRole;
}
}
return false;
}
if(inviter.arrayContains(name))
{
console.log("canceled");
var cancel = button.parentNode.parentNode.children[0];
cancel.click();
}
else if (hasRole(userRole) == false) {
console.log("cancel");
var cancel = button.parentNode.parentNode.children[0];
cancel.click();
}
else if (button.textContent.indexOf("Connect")<0){
console.log("skipped");
inviter.userList.push(name); // it's likely that this person didn't join linkedin in the meantime, so we'll ignore them
var cancel = button.parentNode.parentNode.children[0];
cancel.click();
}
else {
console.log("added");
inviter.userList.push(name);
button.click();
}
};
inviter.arrayContains = function(item)
{
return (inviter.userList.indexOf(item) > -1);
};
inviter.usersJson = {};
inviter.loadResult = function()
{
var retrievedObject = localStorage.getItem('inviterList');
var temp = JSON.stringify(retrievedObject);
inviter.userList = JSON.parse(temp);
};
inviter.saveResult = function()
{
inviter.usersJson = JSON.stringify(inviter.userList);
localStorage.setItem('inviterList', inviter.usersJson);
};
setInterval(function () { inviter.invite(); }, 5000);
`
When I try executing this, I get the following error:
VM288:49 Uncaught TypeError: Cannot read property 'children' of undefined
at hasRole (<anonymous>:49:71)
at Object.inviter.handleRepeat (<anonymous>:66:11)
at Object.inviter.invite (<anonymous>:30:69)
at <anonymous>:108:35
Any ideas as to how to fix it?

Problems minifying javascript file (asp.net application)

I have the following javascript code:
class UrlParameters {
constructor() {
this.initVariablesWithDefaultValues();
var serverUrlData = HelperJSViewBag.getValue("UrlData", true);
var urlVariables = serverUrlData ? serverUrlData : HLinks.getAllUrlVariables();
var sessionID = this.convertToString(urlVariables["sessionID"]);
var idSession = this.convertToString(urlVariables["idSession"]);
var sessionid = this.convertToString(urlVariables["sessionid"]);
if (idSession.length > 0)
this.sessionID = idSession;
else if (sessionid.length > 0)
this.sessionID = sessionid;
else
this.sessionID = sessionID;
var countryISO = this.convertToString(urlVariables["countryISO"]);
var country = this.convertToString(urlVariables["country"]);
this.countryISO = countryISO.length > 0 ? countryISO : country;
var productRef = this.convertToString(urlVariables["productRef"]);
var pRef = this.convertToString(urlVariables["ref"]);
var refproduct = this.convertToString(urlVariables["refproduct"]);
var productReference = this.convertToString(urlVariables["productReference"]);
if (productRef.length > 0)
this.productReference = productRef;
else if (pRef.length > 0)
this.productReference = pRef;
else if (refproduct.length > 0)
this.productReference = refproduct;
else
this.productReference = productReference;
var PartnerCode = this.convertToString(urlVariables["PartnerCode"]);
var partnerCode = this.convertToString(urlVariables["partnerCode"]);
this.partnerCode = PartnerCode.length > 0 ? PartnerCode : partnerCode;
var themeReference = this.convertToString(urlVariables["themeReference"]);
var theme = this.convertToString(urlVariables["theme"]);
this.themeReference = themeReference.length > 0 ? themeReference : theme;
this.projectName = this.convertToString(urlVariables["projectName"]);
var coverReference = this.convertToString(urlVariables["coverReference"]);
var refCover = this.convertToString(urlVariables["refCover"]);
this.coverReference = coverReference.length > 0 ? coverReference : refCover;
this.themeFill = this.convertToInt(urlVariables["themeFill"], 0); // 0 -> directly without autofill ; 1 -> not directly without autofill ; 2 -> not directly quick autofill ; 3 -> not directly smart autofill
this.smartOpt = this.convertToInt(urlVariables["smartOpt"], 2); //1->faces,colors,dimentions; 2-> colors and dimentions; 3-> dimentions
var open = this.convertToString(urlVariables["open"]);
var projectCode = this.convertToString(urlVariables["projectCode"]);
this.projectCode = open.length > 0 ? open : projectCode;
this.productCode = this.convertToString(urlVariables["productCode"]);
this.projectID = this.convertToString(urlVariables["projectID"]);
var categoryID = this.convertToInt(urlVariables["categoryID"]);
var cat = this.convertToInt(urlVariables["cat"]);
this.categoryID = categoryID > 0 ? categoryID : cat;
var subCategoryReference = this.convertToString(urlVariables["subCategoryReference"]);
var subCat = this.convertToString(urlVariables["subCat"]);
this.subCategoryReference = subCategoryReference.length > 0 ? subCategoryReference : subCat;
var typeFinishID = this.convertToInt(urlVariables["typeFinishID"]);
var refProdutFinish = this.convertToInt(urlVariables["refProdutFinish"]);
var productTypeFinishID = this.convertToInt(urlVariables["productTypeFinishID"]);
if (typeFinishID > 0)
this.productTypeFinishID = typeFinishID;
else if (refProdutFinish > 0)
this.productTypeFinishID = refProdutFinish;
else
this.productTypeFinishID = productTypeFinishID;
var coverTypeFinishID = this.convertToInt(urlVariables["coverTypeFinishID"]);
var coverFinishID = this.convertToInt(urlVariables["coverFinishID"]);
var refCoverFinish = this.convertToInt(urlVariables["refCoverFinish"]);
if (coverTypeFinishID > 0) this.coverTypeFinishID = coverTypeFinishID;
else if (coverFinishID > 0) this.coverTypeFinishID = coverFinishID;
else this.coverTypeFinishID = refCoverFinish;
var numPages = this.convertToInt(urlVariables["numPages"]);
var refPages = this.convertToInt(urlVariables["refPages"]);
var numberOfPages = this.convertToInt(urlVariables["numberOfPages"]);
if (numPages > 0)
this.numberOfPages = numPages;
else if (refPages > 0)
this.numberOfPages = refPages;
else
this.numberOfPages = numberOfPages;
this.coverType = this.convertToString(urlVariables["coverType"]);
var textureID = this.convertToString(urlVariables["textureID"]);
var textureReference = this.convertToString(urlVariables["textureReference"]);
if (textureID.length > 0) this.textureReference = textureID;
else this.textureReference = textureReference;
var textureColorID = this.convertToString(urlVariables["textureColorID"]);
var textureColorReference = this.convertToString(urlVariables["textureColorReference"]);
var refColor = this.convertToString(urlVariables["refColor"]);
if (textureColorID.length > 0) this.textureColorReference = textureColorID;
else if (refColor.length > 0) this.textureColorReference = refColor;
else this.textureColorReference = textureColorReference;
var windowID = this.convertToString(urlVariables["windowID"]);
var refWindow = this.convertToString(urlVariables["refWindow"]);
var windowReference = this.convertToString(urlVariables["windowReference"]);
if (windowID.length > 0)
this.windowReference = windowID;
else if (refWindow.length > 0)
this.windowReference = refWindow;
else
this.windowReference = windowReference;
this.savedProject = this.convertToBoolean(urlVariables["savedProject"]);
this.startMonth = this.convertToInt(urlVariables["startMonth"]);
this.startYear = this.convertToInt(urlVariables["startYear"]);
this.wantHolidays = this.convertToBoolean(urlVariables["wantHolidays"]);
var frameID = this.convertToString(urlVariables["frameID"]);
var frameReference = this.convertToString(urlVariables["frameReference"]);
var canvasRef = this.convertToString(urlVariables["canvasRef"]);
if (frameID.length > 0)
this.frameReference = frameID;
else if (canvasRef.length > 0)
this.frameReference = canvasRef;
else
this.frameReference = frameReference;
this.frameReference = frameID.length > 0 ? frameID : frameReference;
var colorFrameID = this.convertToString(urlVariables["colorFrameID"]);
var frameColorReference = this.convertToString(urlVariables["frameColorReference"]);
var canvasColor = this.convertToString(urlVariables["canvasColor"]);
if (colorFrameID.length > 0)
this.frameColorReference = colorFrameID;
else if (canvasColor.length > 0)
this.frameColorReference = canvasColor;
else
this.frameColorReference = frameColorReference;
this.albumXML = this.convertToString(urlVariables["albumXML"]);
this.pagesXML = this.convertToString(urlVariables["pagesXML"]);
var languageISO = this.convertToString(urlVariables["languageISO"]);
var lang = this.convertToString(urlVariables["lang"]);
if (languageISO.length > 0)
this.languageISO = languageISO;
else if (lang.length > 0)
this.languageISO = lang;
this.openThemeAccordion = this.convertToBoolean(urlVariables["openThemeAccordion"]);
var galleryID = this.convertToString(urlVariables["galleryID"]);
var galleryReference = this.convertToString(urlVariables["galleryReference"]);
this.galleryReference = galleryID.length > 0 ? galleryID : galleryReference;
var login_page = this.convertToString(urlVariables["login_page"]);
var Login_Page = this.convertToString(urlVariables["Login_Page"]);
this.Login_Page = this.convertToBoolean(login_page.length > 0 ? login_page : Login_Page);
this.forceMobile = this.convertToBoolean(urlVariables["forceMobile"]);
this.clientApplication = this.convertToString(urlVariables["clientApplication"]);
this.goToPreview = this.convertToInt(urlVariables["goToPreview"]);
this.orderID = this.convertToInt(urlVariables["orderID"], -1);
this.CID = this.convertToString(urlVariables["CID"]);
this.unblock = this.convertToBoolean(urlVariables["unblock"]);
var idPartner = this.convertToInt(urlVariables["idPartner"]);
var partnerID = this.convertToInt(urlVariables["partnerID"]);
var idEmp = this.convertToInt(urlVariables["idEmp"]);
this.forceException = this.convertToBoolean(urlVariables["forceException"]);
if (idPartner > 0)
this.partnerID = idPartner;
else if (partnerID > 0)
this.partnerID = partnerID;
else if (idEmp > 0)
this.partnerID = idEmp;
this.goDirectlyToEditor = this.convertToBoolean(urlVariables["goDirectlyToEditor"]);
}
static getInstance() {
if (typeof UrlParameters.urlParameters === "undefined")
UrlParameters.urlParameters = new UrlParameters();
return UrlParameters.urlParameters;
}
getData() {
return {
sessionID : this.sessionID,
countryISO: this.countryISO,
productReference: this.productReference,
partnerCode: this.partnerCode,
themeReference: this.themeReference,
projectName: this.projectName,
coverReference: this.coverReference,
themeFill: this.themeFill,
smartOpt: this.smartOpt,
projectCode: this.projectCode,
productCode: this.productCode,
projectID: this.projectID,
categoryID: this.categoryID,
subCategoryReference: this.subCategoryReference,
productTypeFinishID: this.productTypeFinishID,
coverTypeFinishID: this.coverTypeFinishID,
numberOfPages: this.numberOfPages,
coverType: this.coverType,
textureReference: this.textureReference,
textureColorReference: this.textureColorReference,
windowReference: this.windowReference,
savedProject: this.savedProject,
startMonth: this.startMonth,
startYear: this.startYear,
wantHolidays: this.wantHolidays,
frameReference: this.frameReference,
frameColorReference: this.frameColorReference,
albumXML: this.albumXML,
pagesXML: this.pagesXML,
languageISO: this.languageISO,
openThemeAccordion: this.openThemeAccordion,
galleryReference: this.galleryReference,
Login_Page: this.Login_Page,
forceMobile: this.forceMobile,
clientApplication: this.clientApplication,
goToPreview: this.goToPreview,
orderID: this.orderID,
CID: this.CID,
unblock: this.unblock,
partnerID: this.partnerID,
forceException: this.forceException,
goDirectlyToEditor: this.goDirectlyToEditor
}
}
getVariableOnce(name) {
if (!this.variableOnce) this.variableOnce = this.getData();
var value = this.variableOnce[name];
delete this.variableOnce[name];
return value;
}
initVariablesWithDefaultValues() {
this.projectName = "";
this.productReference = "";
this.coverReference = "";
this.textureReference = "";
this.colorReference = "";
this.windowReference = "";
this.numberOfPages = 0;
this.productTypeFinishID = 0;
this.coverTypeFinishID = 0;
this.canvasColor = "";
this.projectCode = "";
this.sessionID = "";
this.countryISO = "";
this.themeReference = "";
this.themeFill = 0;
this.smartOpt = 2;
this.projectID = "";
this.productCode = "";
this.categoryID = -1;
this.savedProject = false;
this.startMonth = 0;
this.startYear = 0;
this.wantHolidays = false;
this.albumXML = "";
this.pagesXML = "";
this.languageISO = "";
this.Login_Page = false;
this.frameReference = "";
this.frameColorReference = "";
this.partnerCode = "";
this.partnerID = "";
this.coverType = "";
this.textureColorReference = ""
this.subCategoryReference = "";
this.openThemeAccordion = false;
this.galleryReference = "";
this.clientApplication = "";
this.forceMobile = false;
this.idUpload = 0;
this.orderID = -1;
this.idControl = 0;
this.goToPreview = 0;
this.unblock = false;
this.CID = "";
this.forceException = false;
this.goDirectlyToEditor = false;
}
convertToString(value, defaultValue) {
if (typeof defaultValue !== "var") defaultValue = "";
if (value)
return value;
else
return defaultValue;
}
convertToInt(value, defaultValue) {
if (typeof defaultValue !== "number") defaultValue = 0;
if (value)
return parseInt(value);
else
return defaultValue;
}
convertToBoolean(value, defaultValue) {
if (typeof defaultValue !== "boolean") defaultValue = false;
if (value)
return value;
else
return defaultValue;
}
}
When I run my application with the BundleTable.EnableOptimizations = true the asp.net does not minify this files. Istead, return a new file with the following errors:
/* Minification failed. Returning unminified contents.
(1,1-6): run-time error JS1195: Expected expression: class
(3,19-20): run-time error JS1004: Expected ';': {
(201,12-23): run-time error JS1004: Expected ';': getInstance
(201,26-27): run-time error JS1004: Expected ';': {
(208,15-16): run-time error JS1004: Expected ';': {
(256,27-28): run-time error JS1004: Expected ';': {
(265,38-39): run-time error JS1004: Expected ';': {
(314,42-43): run-time error JS1004: Expected ';': {
(323,39-40): run-time error JS1004: Expected ';': {
(332,43-44): run-time error JS1004: Expected ';': {
(341,1-2): run-time error JS1002: Syntax error: }
(336,13-25): run-time error JS1018: 'return' statement outside of function: return value
(338,13-32): run-time error JS1018: 'return' statement outside of function: return defaultValue
(327,13-35): run-time error JS1018: 'return' statement outside of function: return parseInt(value)
(329,13-32): run-time error JS1018: 'return' statement outside of function: return defaultValue
(318,13-25): run-time error JS1018: 'return' statement outside of function: return value
(320,13-32): run-time error JS1018: 'return' statement outside of function: return defaultValue
(262,9-21): run-time error JS1018: 'return' statement outside of function: return value
(209,9,253,10): run-time error JS1018: 'return' statement outside of function: return {
sessionID : this.sessionID,
countryISO: this.countryISO,
productReference: this.productReference,
partnerCode: this.partnerCode,
themeReference: this.themeReference,
projectName: this.projectName,
coverReference: this.coverReference,
themeFill: this.themeFill,
smartOpt: this.smartOpt,
projectCode: this.projectCode,
productCode: this.productCode,
projectID: this.projectID,
categoryID: this.categoryID,
subCategoryReference: this.subCategoryReference,
productTypeFinishID: this.productTypeFinishID,
coverTypeFinishID: this.coverTypeFinishID,
numberOfPages: this.numberOfPages,
coverType: this.coverType,
textureReference: this.textureReference,
textureColorReference: this.textureColorReference,
windowReference: this.windowReference,
savedProject: this.savedProject,
startMonth: this.startMonth,
startYear: this.startYear,
wantHolidays: this.wantHolidays,
frameReference: this.frameReference,
frameColorReference: this.frameColorReference,
albumXML: this.albumXML,
pagesXML: this.pagesXML,
languageISO: this.languageISO,
openThemeAccordion: this.openThemeAccordion,
galleryReference: this.galleryReference,
Login_Page: this.Login_Page,
forceMobile: this.forceMobile,
clientApplication: this.clientApplication,
goToPreview: this.goToPreview,
orderID: this.orderID,
CID: this.CID,
unblock: this.unblock,
partnerID: this.partnerID,
forceException: this.forceException,
goDirectlyToEditor: this.goDirectlyToEditor
}
(205,9-43): run-time error JS1018: 'return' statement outside of function: return UrlParameters.urlParameters
*/
I search a lot on the internet but I didn't find any solution for this case. Maybe, it's because I'm using the ES6 standard?
I'm using the 1.1.0.0 version of System.Web.Optimization.
System.Web.Optimization doesn't support ES6 syntax
I suggest you to integrate gulp, grunt or webpack into your build process in order to minify your scripts

JSOM dynamicly get two announcements from all lists in all webs

Need help with the chaining. The functions work. But async calls make it hard for me to get everything. Help me think right!
My thought:
Get All Webs recursively (function works)
Get all lists from webs and iff announcementlist add to array and pass along
Get two items from all announcmentlists and sort by created.
Add ALL announcement items into one large array (to be able to sort array later.
Heres the code,
function getAllWebs(success, error) {
var ctx = SP.ClientContext.get_current();
var web = ctx.get_site().get_rootWeb();
var result = [];
var level = 0;
result.push(web);
var getAllWebsInner = function (web, result, success, error) {
level++;
var ctx = web.get_context();
var webs = web.get_webs();
ctx.load(webs, 'Include(Title,Webs,ServerRelativeUrl)');
ctx.executeQueryAsync(
function () {
for (var i = 0; i < webs.get_count() ; i++) {
var web = webs.getItemAtIndex(i);
result.push(web);
if (web.get_webs().get_count() > 0) {
getAllWebsInner(web, result, success, error);
}
}
level--;
if (level == 0 && success)
success(result);
},
error);
};
getAllWebsInner(web, result, success, error);
}
function error(sender, args) {
console.log(args.get_message());
};
function getAnnouncementLists(web, success, error) {
var dfd = $.Deferred();
var ctx = web.get_context();
var collList = web.get_lists();
var result = []
ctx.load(collList, 'Include(Title, Id, BaseTemplate)');
ctx.executeQueryAsync(function () {
for (var i = 0; i < collList.get_count() ; i++) {
var list = collList.getItemAtIndex(i);
var bTemp = list.get_baseTemplate();
if (bTemp == 104) {
result.push(list);
}
}
//success(result);
dfd.resolve(result);
}, error);
return dfd.promise();
}
function getListItems(list, success, error) {
var dfd = $.Deferred();
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><OrderBy><FieldRef Name="Created" Ascending="False"></FieldRef>'
+ '</OrderBy></Query><ViewFields><FieldRef Name="Title"/><FieldRef Name="Body"/>' +
'<FieldRef Name="Created"/></ViewFields><RowLimit>2</RowLimit></View>');
var listItems = list.getItems(camlQuery);
var result = []
var ctx = list.get_parentWeb().get_context();
ctx.load(listItems);
ctx.executeQueryAsync(function () {
for (var i = 0; i < listItems.get_count() ; i++) {
var item = listItems.getItemAtIndex(i);
result.push(item);
}
dfd.resolve(result);
//success(result);
}, error);
return dfd.promise();
}
function printResults(items) {
var sortedItems = items.sort(dynamicSort("get_created()"));
alert(sortedItems);
}
function dynamicSort(property) {
var sortOrder = 1;
if (property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function (a, b) {
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
$(document).ready(function () {
var items = getAllWebs(
function (allwebs) {
var array = [];
for (var i = 0; i < allwebs.length; i++) {
getAnnouncementLists(allwebs[i]).then(function (announceLists) {
for (var i = 0; i < announceLists.length; i++) {
getListItems(announceLists[i]).then(function (items) {
array.push(items);
});
}
});
}
return array;
}
);
//getAllWebs(
// function (allwebs) {
// for (var i = 0; i < allwebs.length; i++) {
// getAnnouncementLists(allwebs[i],
// function (announceLists) {
// for (var i = 0; i < announceLists.length; i++) {
// getListItems(announceLists[i],
// function (items) {
// printResults(items);
// }, error);
// }
// }, error);
// }
// }, error);
});
Given the requirements to retrieve list items from Announcements lists located across site collection, below is demonstrated the modified example that contains some improvements such as:
the number of requests to the server is reduced
fixed the issue in getAllWebs function that prevents to return any results if site contains only a root web
Example
function getAllWebs(propertiesToRetrieve,success, error) {
var ctx = SP.ClientContext.get_current();
var web = ctx.get_site().get_rootWeb();
var result = [];
var level = 0;
ctx.load(web, propertiesToRetrieve);
result.push(web);
var getAllWebsInner = function (web, result, success, error) {
level++;
var ctx = web.get_context();
var webs = web.get_webs();
var includeExpr = 'Include(Webs,' + propertiesToRetrieve.join(',') + ')';
ctx.load(webs, includeExpr);
ctx.executeQueryAsync(
function () {
for (var i = 0; i < webs.get_count() ; i++) {
var web = webs.getItemAtIndex(i);
result.push(web);
if (web.get_webs().get_count() > 0) {
getAllWebsInner(web, result, success, error);
}
}
level--;
if (level == 0 && success)
success(result);
},
error);
};
getAllWebsInner(web, result, success, error);
}
function loadListItems(lists,query,success,error,results){
var results = results || [];
var curList = lists[0];
var ctx = curList.get_context();
var listItems = curList.getItems(query);
ctx.load(listItems);
ctx.executeQueryAsync(function () {
results.push.apply(results, listItems.get_data());
lists.shift();
if(lists.length > 0) {
loadListItems(lists,query,success,error,results);
}
if(lists.length == 0)
success(results);
}, error);
}
function dynamicSort(property) {
var sortOrder = 1;
if (property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function (a, b) {
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
var propertiesToRetrieve = ['Lists.Include(BaseTemplate)','ServerRelativeUrl'];
getAllWebs(propertiesToRetrieve,
function(allwebs){
//1. get filtered lists
var allAnnouncementLists = [];
allwebs.forEach(function(w){
var announcementLists = w.get_lists().get_data().filter(function(l){
if(l.get_baseTemplate() == SP.ListTemplateType.announcements)
return l;
});
allAnnouncementLists.push.apply(allAnnouncementLists, announcementLists);
});
//2.Load list items from lists
var query = new SP.CamlQuery(); //<-set your custom query here
loadListItems(allAnnouncementLists,query,
function(allListItems){
//3.Sort and print results
var sortedItems = allListItems.sort(dynamicSort("get_created()"));
sortedItems.forEach(function(item){
console.log(item.get_item('Title'));
});
},logError);
},
logError);
function logError(sender,args){
console.log(args.get_message());
}

How to stop execution for function with Userscript

The Website I want to write an Userscript for has something like that:
p.Stream = p.Class.extend({
.
.
.
_processResponse: function(data) {
if (!data.items || !data.items.length) {
return null;
}
this.reached.start = data.atStart || this.reached.start;
this.reached.end = data.atEnd || this.reached.end;
var oldestId, newestId;
if (this.options.promoted) {
data.items.sort(p.Stream.sortByPromoted);
oldestId = data.items[data.items.length - 1].promoted;
newestId = data.items[0].promoted;
} else {
data.items.sort(p.Stream.sortById);
oldestId = data.items[data.items.length - 1].id;
newestId = data.items[0].id;
}
var position = (oldestId < this._oldestId) ? p.Stream.POSITION.APPEND : p.Stream.POSITION.PREPEND;
this._oldestId = Math.min(this._oldestId, oldestId);
this._newestId = Math.max(this._newestId, newestId);
var prev = null;
var itemVotes = p.user.voteCache.votes.items;
for (var i = 0; i < data.items.length; i++) {
var item = data.items[i];
item.thumb = CONFIG.PATH.THUMBS + item.thumb;
item.image = CONFIG.PATH.IMAGES + item.id;
item.fullsize = item.fullsize ? CONFIG.PATH.FULLSIZE + item.fullsize : null;
item.vote = itemVotes[item.id] || 0;
this.items[item.id] = item;
}
return position;
}
});
I want to manipulate the _processResponse such that item.image points to another Source. Is this possible with Userscripts? I tried overriding the function like stated on some websites but that does not work like expected. I just want to override this function, nothing other than that.
As far as I can see, the easiest and most flexible way to do that would be to wrap _processResponse in a function that further operates on data after the original function is called:
var oldfunc = p.Stream.prototype._processResponse;
p.Stream.prototype._processResponse = function(data) {
var ret = oldfunc.apply(this, arguments);
if(data.items && data.items.length)
{
for(var i = 0, len = data.items.length; i < len; ++i)
{
data.items[i].image = 'https://example.com/a.png'; // or whatever
}
}
return ret;
}

Categories