I have the following code which reads information from a sharepoint list and renders fine in google chrome, but when tested in IE 11 (Corporate Browser), then I get the following exception:
ReferenceError: 'Promise' is undefined
at getContentTypeOfCurrentItem (https://ourserver.com/sites/billing/Style%20Library/xxx/Angular/related-billing-documents-controller.js:209:5)
at addContentType (https://ourserver.com/sites/billing/Style.com/sites/billing/Style%20Library/xxx/Angular/related-billing-documents-controller.js:201:5)
at Anonymous function (https://ourserver.com/sites/billing/Style%20Library/xxx/Angular/related-billing-documents-controller.js:163:7)
at Anonymous function (https://ourserver.com/sites/billing/Style%20Library/xxx/Angular/angular.min.js:130:399)
at m.prototype.$eval (https://ourserver.com/sites/billing/Style%20Library/xxx/Angular/angular.min.js:145:96)
at m.prototype.$digest (https://ourserver.com/sites/billing/Style%20Library/xxx/Angular/angular.min.js:142:165)
at Anonymous function (https://ourserver.com/sites/billing/Style%20Library/xxx
(function () {
angular
.module('BillCycleApp')
.controller('relatedBillingDocumentsController', ['$scope', '$log', '$q', 'spService', 'BillingDocuments', 'General',
function ($scope, $log, $q, spService, config, generalConfig) {
var vm = this;
var tableSelector = "#related-billing-documents-table";
var componentSelector = ".related-billing-documents";
function GetContext() {
vm.Name = config.Name;
var dataTableColumns = spService.TransformFieldsToDataTableColumns(config.FieldsToShow);
$.fn.dataTable.moment( generalConfig.DateTimeFormat );
// Initialize with empty data
$(tableSelector).DataTable({
data : [],
columns : dataTableColumns,
order : config.SortOrder,
deferRender : true
}).on( 'draw.dt', function ( e, settings, processing ) {
// Make sure the UserPresence is added every time the DataTable's data changes (paging, sorting, search,..)
spService.UserPresenceComponent.AddPresence();
});
// Make component visible
$(componentSelector).css("visibility", "visible");
// SP.js function
// Get Bill Cycle list & id
var listItemId = GetUrlKeyValue('ID', true, window.location.search, true);
var listId = "{" + GetUrlKeyValue('List', true, window.location.search, true) + "}";
var propertiesToLoad = ["FileRef","PwC_ClientCode","PwC_JobCodesMulti","PwC_EngagementCode"];
spService.GetListItem(listId, listItemId, propertiesToLoad)
.then(function(billCycle) {
var listItemValues = [];
propertiesToLoad
.forEach(function(propertyName) {
var value = billCycle.get_item(propertyName);
listItemValues[propertyName] = value;
});
var billCyclePath = _spPageContextInfo.siteAbsoluteUrl;
billCyclePath += listItemValues["FileRef"];
var clientCode = listItemValues["PwC_ClientCode"]
var jobCodesLookups = listItemValues["PwC_JobCodesMulti"];
var engagementCode = listItemValues["PwC_EngagementCode"]
var jobCodes = [];
if(jobCodesLookups) {
jobCodesLookups.forEach(function(lookup) {
jobCodes.push(lookup.get_lookupValue());
});
}
// Get data with parameters
GetData(billCyclePath, clientCode, jobCodes, engagementCode);
});
}
function GetData(billCyclePath, clientCode, jobCodes, engagementCode) {
var enhanceFunctions = [
function(searchResultRow) {
return spService.AddHyperLinkOnFields(searchResultRow, config.HyperLinks);
},
function(searchResultRow) {
return spService.AddPresenceOnFields(searchResultRow, config.UserFields);
},
function(searchResultRow) {
return spService.FormatDateFields(searchResultRow, config.DateFields, generalConfig.DateTimeFormat);
},
function(searchResultRow) {
return spService.AddImageMapping(searchResultRow, config.ImageFields);
},
function(searchResultRow) {
return spService.FormatNumberFields(searchResultRow, config.NumberFields);
},
function(searchResultRow) {
// Put link to parent Bill Cycle with name = folder name
//var parentLink = searchResultRow["FileRef"];
//arrayofstrings = parentLink.split("/");
//var billCycleFolderName = arrayofstrings[arrayofstrings.length-2];
//arrayofstrings.pop();
//var hyperLink = '' + billCycleFolderName + '';
//searchResultRow["Bill Cycle"] = hyperLink;
}
];
// Get data from SP
var selectProperties = spService.TransformFieldsToSelectProperties(config.Fields); // copy array
var selectPropertiesToShow = spService.TransformFieldsToSelectProperties(config.FieldsToShow); // copy array
var extendedSelectProperties = selectProperties.slice();
var hyperLinkedProperties = spService.TransformFieldsToSelectProperties(config.HyperLinks)
extendedSelectProperties = extendedSelectProperties.concat(hyperLinkedProperties);
GetRelatedBillingDocumentsFromList(extendedSelectProperties, billCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions)
.then(function (data) {
var trimmedData = spService.SpSearchQuery.TrimSearchResultsToSelectProperties(data, selectPropertiesToShow);
// Add data to dataTable
var dataTable = $(tableSelector).DataTable();
dataTable.clear().rows.add(trimmedData).columns.adjust().draw(); // Resize columns based on new data sizes
vm.ValidDataLoaded = true;
})
.catch (function (message) {
vm.Name = "Error";
vm.ValidDataLoaded = true;
});
}
function GetRelatedBillingDocumentsFromList(selectProperties, currentBillCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions) {
$log.info("Retrieving related billing documents for bill cycle with name [" + currentBillCyclePath + "]");
var deferred = $q.defer();
var webUrl = _spPageContextInfo.webAbsoluteUrl;
selectProperties = selectProperties.concat("ContentTypeId");
var viewFields = spService.ConvertSelectPropertiesToViewFields(selectProperties);
// query must return the documents for the same client but in other bill cycles not the current one
var camlQuery = '<View Scope="RecursiveAll">' + viewFields +
'<Query>' +
'<Where>' +
'<And>' +
'<Eq>' +
'<FieldRef Name="PwC_ClientCode" />' +
'<Value Type="Text">'+ clientCode + '</Value>' +
'</Eq>' +
'<Neq>' +
'<FieldRef Name="ContentType" />' +
'<Value Type="Computed">Bill Cycle</Value>' +
'</Neq>' +
'</And>' +
'</Where>' +
'</Query>' +
'</View>';
var billCyclesListId = "{c23bbae4-34f7-494c-8f67-acece3ba60da}";
spService.GetListItems(billCyclesListId, camlQuery, selectProperties)
.then(function(listItems) {
var listItemsWithValues = [];
if(listItems) {
var enumerator = listItems.getEnumerator();
var promises = [];
while (enumerator.moveNext()) {
var listItem = enumerator.get_current();
var listItemValues = [];
selectProperties
.forEach(function(propertyName) {
var value = listItem.get_item(propertyName);
if(propertyName === "PwC_JobCodesMulti"){
jobvalue = "";
value.forEach(function(jobvalues){
jobvalue+= jobvalues.get_lookupValue() +";";
})
listItemValues[propertyName] = jobvalue;
}else{
listItemValues[propertyName] = value;
}
});
listItemsWithValues.push(listItemValues);
}
var promises = listItemsWithValues.map(addContentType);
Promise.all(promises).then(youCanUseTheData);
function youCanUseTheData(){
/*
At this point, each listItem holds the 'Document Type' info
*/
listItemsWithValues.forEach(function(listItem) {
var fileDirRef = listItem["FileRef"];
var id = listItem["ID"];
var title = listItem["Title"];
var serverUrl = _spPageContextInfo.webAbsoluteUrl.replace(_spPageContextInfo.webServerRelativeUrl,"");
var dispFormUrl = serverUrl + "/sites/billing/_layouts/15/DocSetHome.aspx?id="+fileDirRef;
var parentLink = listItem["FileRef"];
arrayofstrings = parentLink.split("/");
var billCycleFolderName = arrayofstrings[arrayofstrings.length-2];
arrayofstrings.pop();
var hyperLink = '' + billCycleFolderName + '';
listItem["Bill Cycle"] = hyperLink;
listItemsWithValues["Document Type"] = getContentTypeOfCurrentItem(listItem.ID.toString());
});
var enhancedListItemValues = spService.SpSearchQuery.EnhanceSearchResults(listItemsWithValues, enhanceFunctions);
deferred.resolve(listItemsWithValues);
}
}
})
.catch (function (message) {
deferred.reject();
});
return deferred.promise;
}
function addContentType(listItem){
//return getContentTypeOfCurrentItem(listItem.ID.toString());
return getContentTypeOfCurrentItem(listItem.ID.toString()).then(function(cname) {
listItem['Document Type'] = cname; //we add the doc type to each listItem, not only the last one
}).catch(function(error) {
$log.warn("Server error");
});
}
function getContentTypeOfCurrentItem(id) {
return new Promise(function (resolve, reject) {
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle("Bill Cycles");
var listItem2 = oList.getItemById(id);
listContentTypes = oList.get_contentTypes();
clientContext.load(listContentTypes);
clientContext.load(listItem2, 'ContentTypeId');
clientContext.executeQueryAsync(
function() {
$log.info("Successfully retrieved getContentTypeOfCurrentItemt");
var ctid = listItem2.get_item("ContentTypeId").toString();
var ct_enumerator = listContentTypes.getEnumerator();
while (ct_enumerator.moveNext()) {
var ct = ct_enumerator.get_current();
if (ct.get_id().toString() == ctid) {
var contentTypeName = ct.get_name();
}
}
return resolve(contentTypeName);
},
function(error, errorInfo) {
$log.warn("Retrieving getContentTypeOfCurrentItem failed");
return reject(errorInfo);
}
);
});
}
function GetRelatedBillingDocuments(selectProperties, currentBillCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions) {
$log.info("Retrieving related billing documents for bill cycle with path [" + currentBillCyclePath + "]");
var deferred = $q.defer();
var webUrl = _spPageContextInfo.webAbsoluteUrl;
// TODO: AND or OR?
var jobCodesFilter = spService.ExpandSearchFilterForEachValue("JobCodes", ":", jobCodes, false, false);
var engagementCodeFilter = "";
if (engagementCode != undefined && engagementCode != "") {
engagementCodeFilter = "EngagementCode:" + engagementCode;
}
if(jobCodesFilter && engagementCodeFilter) {
jobCodesFilter += " OR ";
}
// TODO: Add use of result source?
var queryText = "-Path:" + spService.AddQuotes(currentBillCyclePath) + ' AND -ContentType:"Bill Cycle" AND ClientCode:' + clientCode + " AND (" + jobCodesFilter + engagementCodeFilter + ")";
var searchQuery = new spService.SpSearchQuery(webUrl, queryText, selectProperties, config.ResultSourceName, config.ResultSourceLevel);
searchQuery
.ExecuteSearchQueryFetchAll() // returns deferred
.then(function (results) {
$log.info("Successfully retrieved search results");
var searchResults = spService.SpSearchQuery.EnhanceSearchResults(results, enhanceFunctions);
deferred.resolve(searchResults);
});
return deferred.promise;
}
ExecuteOrDelayUntilScriptLoaded(GetContext, 'sp.js');
}
]); // End Controller()
}()); // End IFFE
Promise is part of ES6 standard that is not fully supported by IE11, you can use babel-polyfill instead or use another librairy like q which is part of angularjs
I am a newbie in nodejs.
I have this Script: book.js
var page = 0;
exports.setPageCount = function (count) {
page = count;
}
exports.getPageCount = function(){
return page;
}
Along with the follownig script: scripts.js
var bookA = require('./book');
var bookB = require('./book');
bookA.setPageCount(10);
bookB.setPageCount(20);
console.log("Book A Pages : " + bookA.getPageCount());
console.log("Book B Pages : " + bookB.getPageCount());
The Output I get:
Book A Pages : 20
Book B Pages : 20
So, I modified script:
module.exports = function(){
var page = 0;
setPageCount : function(count){
page = count;
},
getPageCount : function(){
return page;
}
}
I am expecting the following output:
Book A Pages : 10
Book B Pages : 20
But still getting the original outcome, does anyone have an idea where I made an error?
There are a few ways to go about this and your last attempt is almost a valid one -- modify your module like so:
module.exports = function() {
var pages = 0;
return {
getPageCount: function() {
return pages;
},
setPageCount: function(p) {
pages = p;
}
}
}
and your usage like so:
var bookFactory = require('./book');
var bookA = bookFactory();
var bookB = bookFactory();
bookA.setPageCount(10);
bookB.setPageCount(20);
console.log("Book A Pages : " + bookA.getPageCount());
console.log("Book B Pages : " + bookB.getPageCount());
So I'm crawling a page, collecting links, then I would like to crawl those links to complete my dataset. Here's some code:
crawl.js:
var casper = require("casper").create({
waitTimeout: 3000,
pageSettings: {
userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:23.0) Gecko/20130404 Firefox/23.0"
},
clientScripts: ["includes/jquery.min.js"],
verbose: true
});
var followers = require('./followers');
var currentPage = 1;
var x = require('casper').selectXPath;
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++
}
return size;
};
var collectFollowers = function() {
var url;
this.echo("capturing page " + currentPage);
this.capture("wowhead-p" + currentPage + ".png");
// don't go too far down the rabbit hole
if (currentPage >= 5 || !this.exists(x('//*[text()="Next ›"]'))) {
processFollowers.call(casper);
return terminate.call(casper);
}
currentPage++;
this.echo("requesting next page: " + currentPage);
url = this.getCurrentUrl();
var links = this.evaluate(function() {
var obj = {}
$('.listview-cleartext').map(function(){
obj[$(this).text()] = $(this).attr('href');
});
return obj;
});
for (key in links) {
followers.followers[key] = links[key];
}
this.echo("Page links: " + Object.size(followers.followers));
//this.emit('update.followers', links);
this.thenClick(x('//*[text()="Next ›"]')).then(function() {
this.waitFor(function() {
return url !== this.getCurrentUrl();
}, collectFollowers, processFollowers);
});
};
var processFollowers = function() {
this.echo("Total followers:" + Object.size(followers.followers));
this.each(Object.keys(followers.followers), function(casper, key) {
this.thenOpen('http://wowhead.com' + followers.followers[key]).then(function() {
this.echo("On http://wowhead.com" + followers.followers[key]);
this.evaluate(function() {
this.echo("Inside the evaluate statement.");
if ($('a[href=#quests]').length) {
this.echo("Has quest!");
$('a[href=#quests]').click();
var questURL = $('#tab-quests').show().find('.listview-cleartext').attr('href');
var questName = $('#tab-quests').show().find('.listview-cleartext').text();
this.echo("Quest URL: " + questURL);
followers.followers[key] = {"name": key, "quest": {"url": questURL, "name": questName}};
} else {
this.echo("Does not have quest!");
}
});
});
});
}
var terminate = function() {
this.echo("Done.").exit();
}
casper.start("http://wowhead.com/followers=2");
casper.waitForSelector(x('//*[text()="Next ›"]'), collectFollowers, processFollowers);
casper.run();
followers.js:
var require = patchRequire(require);
var utils = require('utils');
var followers = {};
exports.followers = followers;
followers is used to store a global variable, an object that I continually build and update as I crawl pages. So I go through 3 pages of data, collect links successfully, then begin to process them. As it stands, CasperJS appears to open each page successfully, however the evaluate function is never called.
I was able to get this functionality to work within PhantomJS with some async logic, but switched to casper because it appeared as though this would be taken care of under the hood. I've tried various combinations of thenOpen(), then() and open(), thenOpen() without the then(), etc.. What am I messing up?
casper.evalute() is the sandboxed page context in the same way the as the PhantomJS version (page.evaluate()). It has no access to variables defined outside.
this inside of evaluate() refers to window and not casper and I doubt that there is such a function like window.echo(). If you want to receive console messages from the page context, you need to register to the remote.message event:
casper.on("remote.message", function(msg){
this.echo("remote: " + msg);
});
You have to explicitly pass the result out of the page context and add it there:
var result = this.evaluate(function() {
console.log("Inside the evaluate statement.");
if ($('a[href=#quests]').length) {
console.log("Has quest!");
$('a[href=#quests]').click();
var questURL = $('#tab-quests').show().find('.listview-cleartext').attr('href');
var questName = $('#tab-quests').show().find('.listview-cleartext').text();
console.log("Quest URL: " + questURL);
return {"url": questURL, "name": questName}};
} else {
console.log("Does not have quest!");
return null;
}
});
if (result) {
followers.followers[key] = {name: key, quest: result};
}
I want to set a div's text to "not found" in case the script fails to get the url in the script. I am using jQuery 1.4 version and I have to continue with it for some reason. Can anyone suggest some good ideas?
javascript
$(document).ready(function () {
$("#slides").html("");
$.get('someURl',
function (d) {
var i = 0;
var array = [];
var anchorImg = '';
$(d).find('entry').each(function () {
anchorImg = "<img id='imageID" + i + "' width='480' height='380'/>"
$("#slides").append(anchorImg);
var $entry = $(this);
var pic = $entry.find('content').attr('src');
array[i] = pic;
var ankita = "imageID" + i;
document.getElementById(ankita).src = array[i];
i++;
});
});
});
1.4 does not have deferred functions so your only option is to convert the $.get to a $.ajax call and use the error handler:
$.ajax({
method: 'GET',
url: 'someURl',
success: function(d) {
var i = 0;
var array = [];
var anchorImg = '';
$(d).find('entry').each(function() {
anchorImg= "<img id='imageID" + i + "' width='480' height='380'/>"
$("#slides").append(anchorImg);
var $entry = $(this);
var pic = $entry.find('content').attr('src');
array[i] = pic;
var ankita = "imageID" + i;
document.getElementById(ankita).src = array[i];
i++;
});
},
error: function() {
$('#slides').text('Not found');
}
});
You really should be pushing to use the latest version of jQuery though. 1.4 is nearly 4 years out of date!
I am using this script to store the user's history to a cookie for the last 10 pages accessed. So far I've got the script displaying the cookie data using the document.title, and url in a list.
My question is what would be the simplest way to add a page skip feature, that would let me omit certain pages from being added to the history cookie? Everything I've tried hasn't worked, as it's a little bit outside of my knowledge.
Thanks for your time and help.
JS:
(function($){
var history;
function getHistory() {
var tmp = $.cookie("history");
if (tmp===undefined || tmp===null) tmp = "";
if ($.trim(tmp)=="") tmp = [];
else tmp = tmp.split("||");
history = [];
$.each(tmp, function(){
var split = this.split("|");
history.push({
title: split[0],
url: split[1]
});
});
}
function saveHistory() {
var tmp = [];
$.each(history, function(){
tmp.push(this.title+"|"+this.url);
});
$.cookie("history",tmp.join("||"),{ expires: 60, path: "/" });
}
function addToHistory(title,url) {
var newHistory = []
$.each(history, function(){
if (this.url!=url) newHistory.push(this);
});
history = newHistory;
if (history.length>=10) {
history.shift();
}
history.push({
title: title,
url: url
});
saveHistory();
writeHistory();
}
function writeHistory() {
var list = $("<ul />");
$.each(history, function() {
var element = $("<li />");
var link = $("<a />");
link.attr("href",this.url);
link.text(this.title);
element.append(link);
list.append(element);
});
$("#history").empty().append(list);
}
$(document).ready(function(){
getHistory();
var url = document.location.href;
var split = url.split("#");
var title;
if (split.length > 1) {
title = $("#"+split[1]).text();
} else {
title = document.title;
}
if (title===undefined || title===null || $.trim(title)=="") title = url;
addToHistory(title,url);
url = split[0];
$("a[href^='#']").click(function(){
var link = $(this);
var href = link.attr("href");
var linkUrl = url+href;
var title = $(href).text();
if (title===undefined || title===null || $.trim(title)==="") title = linkUrl;
addToHistory(title,linkUrl);
});
});
})(jQuery);
HTML:
<div id="history"></div>
several ways you could approach this... You could keep an Array of urls not to save, or you could put something in the page that would let the script know not to save that page?...
function saveHistory(){
if ($('.no-save-history')) return false;
/*...*/
}
HTML:
< div id="history" class="no-save-history">