How can I refer to a local js file? - javascript

I have a js file that I can't refer to locally.
If I deploy it online and refer to it from there, it works.
<script src="http://acwebsite.azurewebsites.net/scripts/table2excel.js"></script>
But if I copy the text inside the file and refer to a local js file, it is unable to read it.
<script src ="~/Scripts/table2excel.js"></script>
Not sure what to do.
This is the js file:
//table2excel.js
; (function ($, window, document, undefined) {
var pluginName = "table2excel",
defaults = {
exclude: ".noExl",
name: "Table2Excel"
};
// The actual plugin constructor
function Plugin(element, options) {
this.element = element;
// jQuery has an extend method which merges the contents of two or
// more objects, storing the result in the first object. The first object
// is generally empty as we don't want to alter the default options for
// future instances of the plugin
//
this.settings = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.init();
}
Plugin.prototype = {
init: function () {
var e = this;
var utf8Heading = "<meta http-equiv=\"content-type\" content=\"application/vnd.ms-excel; charset=UTF-8\">";
e.template = {
head: "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\">" + utf8Heading + "<head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets>",
sheet: {
head: "<x:ExcelWorksheet><x:Name>",
tail: "</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>"
},
mid: "</x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body>",
table: {
head: "<table>",
tail: "</table>"
},
foot: "</body></html>"
};
e.tableRows = [];
// get contents of table except for exclude
$(e.element).each(function (i, o) {
var tempRows = "";
$(o).find("tr").not(e.settings.exclude).each(function (i, o) {
tempRows += "<tr>" + $(o).html() + "</tr>";
});
e.tableRows.push(tempRows);
});
e.tableToExcel(e.tableRows, e.settings.name, e.settings.sheetName);
},
tableToExcel: function (table, name, sheetName) {
var e = this, fullTemplate = "", i, link, a;
e.uri = "data:application/vnd.ms-excel;base64,";
e.base64 = function (s) {
return window.btoa(unescape(encodeURIComponent(s)));
};
e.format = function (s, c) {
return s.replace(/{(\w+)}/g, function (m, p) {
return c[p];
});
};
sheetName = typeof sheetName === "undefined" ? "Sheet" : sheetName;
e.ctx = {
worksheet: name || "Worksheet",
table: table,
sheetName: sheetName,
};
fullTemplate = e.template.head;
if ($.isArray(table)) {
for (i in table) {
//fullTemplate += e.template.sheet.head + "{worksheet" + i + "}" + e.template.sheet.tail;
fullTemplate += e.template.sheet.head + sheetName + i + e.template.sheet.tail;
}
}
fullTemplate += e.template.mid;
if ($.isArray(table)) {
for (i in table) {
fullTemplate += e.template.table.head + "{table" + i + "}" + e.template.table.tail;
}
}
fullTemplate += e.template.foot;
for (i in table) {
e.ctx["table" + i] = table[i];
}
delete e.ctx.table;
if (typeof msie !== "undefined" && msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer
{
if (typeof Blob !== "undefined") {
//use blobs if we can
fullTemplate = [fullTemplate];
//convert to array
var blob1 = new Blob(fullTemplate, { type: "text/html" });
window.navigator.msSaveBlob(blob1, getFileName(e.settings));
} else {
//otherwise use the iframe and save
//requires a blank iframe on page called txtArea1
txtArea1.document.open("text/html", "replace");
txtArea1.document.write(e.format(fullTemplate, e.ctx));
txtArea1.document.close();
txtArea1.focus();
sa = txtArea1.document.execCommand("SaveAs", true, getFileName(e.settings));
}
} else {
link = e.uri + e.base64(e.format(fullTemplate, e.ctx));
a = document.createElement("a");
a.download = getFileName(e.settings);
a.href = link;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
return true;
}
};
function getFileName(settings) {
return (settings.filename ? settings.filename : "table2excel") +
(settings.fileext ? settings.fileext : ".xlsx");
}
$.fn[pluginName] = function (options) {
var e = this;
e.each(function () {
if (!$.data(e, "plugin_" + pluginName)) {
$.data(e, "plugin_" + pluginName, new Plugin(this, options));
}
});
// chain jQuery functions
return e;
};
})(jQuery, window, document);

If you are using relative path, use below way
src ="./Scripts/table2excel.js"

Related

Problems with ReactJS and ExtJS3

I have page with ExtJS3 and ReactJS.
In order for the React to work in IE11 i use #babel/polifyll
In turn, Babel uses core-js which has this method:
"use strict";
var LIBRARY = __webpack_require__(/*! ./_library */ "./node_modules/core-js/library/modules/_library.js");
var $export = __webpack_require__(/*! ./_export */ "./node_modules/core-js/library/modules/_export.js");
var redefine = __webpack_require__(/*! ./_redefine */ "./node_modules/core-js/library/modules/_redefine.js");
var hide = __webpack_require__(/*! ./_hide */ "./node_modules/core-js/library/modules/_hide.js");
var Iterators = __webpack_require__(/*! ./_iterators */ "./node_modules/core-js/library/modules/_iterators.js");
var $iterCreate = __webpack_require__(/*! ./_iter-create */ "./node_modules/core-js/library/modules/_iter-create.js");
var setToStringTag = __webpack_require__(/*! ./_set-to-string-tag */ "./node_modules/core-js/library/modules/_set-to-string-tag.js");
var getPrototypeOf = __webpack_require__(/*! ./_object-gpo */ "./node_modules/core-js/library/modules/_object-gpo.js");
var ITERATOR = __webpack_require__(/*! ./_wks */ "./node_modules/core-js/library/modules/_wks.js")('iterator');
var BUGGY = !([].keys && 'next' in [].keys()); // Safari has buggy iterators w/o `next`
var FF_ITERATOR = '##iterator';
var KEYS = 'keys';
var VALUES = 'values';
module.exports = function (Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED) {
$iterCreate(Constructor, NAME, next);
var getMethod = function (kind) {
if (!BUGGY && kind in proto) return proto[kind];
switch (kind) {
case KEYS: return function keys() { return new Constructor(this, kind); };
case VALUES: return function values() { return new Constructor(this, kind); }; //AT THIS POINT
} return function entries() { return new Constructor(this, kind); };
}
//SOME PARTS OF THIS METHOD
};
in case VALUES: return function values() { return new Constructor(this, kind); }; i have something which make something and this part of code broke ExtJS3 methods like this:
Ext.XTemplate = function(){
Ext.XTemplate.superclass.constructor.apply(this, arguments);
var me = this,
s = me.html,
re = /<tpl\b[^>]*>((?:(?=([^<]+))\2|<(?!tpl\b[^>]*>))*?)<\/tpl>/,
nameRe = /^<tpl\b[^>]*?for="(.*?)"/,
ifRe = /^<tpl\b[^>]*?if="(.*?)"/,
execRe = /^<tpl\b[^>]*?exec="(.*?)"/,
m,
id = 0,
tpls = [],
VALUES = 'values',
PARENT = 'parent',
XINDEX = 'xindex',
XCOUNT = 'xcount',
RETURN = 'return ',
WITHVALUES = 'with(values){ ';
s = ['<tpl>', s, '</tpl>'].join('');
while((m = s.match(re))){
var m2 = m[0].match(nameRe),
m3 = m[0].match(ifRe),
m4 = m[0].match(execRe),
exp = null,
fn = null,
exec = null,
name = m2 && m2[1] ? m2[1] : '';
if (m3) {
exp = m3 && m3[1] ? m3[1] : null;
if(exp){
fn = new Function(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES + RETURN +(Ext.util.Format.htmlDecode(exp))+'; }');
}
}
if (m4) {
exp = m4 && m4[1] ? m4[1] : null;
if(exp){
exec = new Function(VALUES, PARENT, XINDEX, XCOUNT, WITHVALUES +(Ext.util.Format.htmlDecode(exp))+'; }');
}
}
if(name){
switch(name){
case '.': name = new Function(VALUES, PARENT, WITHVALUES + RETURN + VALUES + '; }'); break;
case '..': name = new Function(VALUES, PARENT, WITHVALUES + RETURN + PARENT + '; }'); break;
default: name = new Function(VALUES, PARENT, WITHVALUES + RETURN + name + '; }');
}
}
tpls.push({
id: id,
target: name,
exec: exec,
test: fn,
body: m[1]||''
});
s = s.replace(m[0], '{xtpl'+ id + '}');
++id;
}
Ext.each(tpls, function(t) {
me.compileTpl(t);
});
me.master = tpls[tpls.length-1];
me.tpls = tpls;
};
Ext.extend(Ext.XTemplate, Ext.Template, {
// private
re : /\{([\w-\.\#]+)(?:\:([\w\.]*)(?:\((.*?)?\))?)?(\s?[\+\-\*\\]\s?[\d\.\+\-\*\\\(\)]+)?\}/g,
// private
codeRe : /\{\[((?:\\\]|.|\n)*?)\]\}/g,
// private
applySubTemplate : function(id, values, parent, xindex, xcount){
var me = this,
len,
t = me.tpls[id],
vs,
buf = [];
if ((t.test && !t.test.call(me, values, parent, xindex, xcount)) ||
(t.exec && t.exec.call(me, values, parent, xindex, xcount))) {
return '';
}
vs = t.target ? t.target.call(me, values, parent) : values;
len = vs.length;
parent = t.target ? values : parent;
if(t.target && Ext.isArray(vs)){
Ext.each(vs, function(v, i) {
buf[buf.length] = t.compiled.call(me, v, parent, i+1, len);
});
return buf.join('');
}
return t.compiled.call(me, vs, parent, xindex, xcount);
},
// private
compileTpl : function(tpl){
var fm = Ext.util.Format,
useF = this.disableFormats !== true,
sep = Ext.isGecko ? "+" : ",",
body;
function fn(m, name, format, args, math){
if(name.substr(0, 4) == 'xtpl'){
return "'"+ sep +'this.applySubTemplate('+name.substr(4)+', values, parent, xindex, xcount)'+sep+"'";
}
var v;
if(name === '.'){
v = 'values';
}else if(name === '#'){
v = 'xindex';
}else if(name.indexOf('.') != -1){
v = name;
}else{
v = "values['" + name + "']";
}
if(math){
v = '(' + v + math + ')';
}
if (format && useF) {
args = args ? ',' + args : "";
if(format.substr(0, 5) != "this."){
format = "fm." + format + '(';
}else{
format = 'this.call("'+ format.substr(5) + '", ';
args = ", values";
}
} else {
args= ''; format = "("+v+" === undefined ? '' : ";
}
return "'"+ sep + format + v + args + ")"+sep+"'";
}
function codeFn(m, code){
return "'"+ sep +'('+code+')'+sep+"'";
}
// branched to use + in gecko and [].join() in others
if(Ext.isGecko){
body = "tpl.compiled = function(values, parent, xindex, xcount){ return '" +
tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn).replace(this.codeRe, codeFn) +
"';};";
}else{
body = ["tpl.compiled = function(values, parent, xindex, xcount){ return ['"];
body.push(tpl.body.replace(/(\r\n|\n)/g, '\\n').replace(/'/g, "\\'").replace(this.re, fn).replace(this.codeRe, codeFn));
body.push("'].join('');};");
body = body.join('');
}
eval(body);
return this;
},
applyTemplate : function(values){
return this.master.compiled.call(this, values, {}, 1, 1);
},
compile : function(){return this;}
});
Ext.XTemplate.prototype.apply = Ext.XTemplate.prototype.applyTemplate;
Ext.XTemplate.from = function(el){
el = Ext.getDom(el);
return new Ext.XTemplate(el.value || el.innerHTML);
};/*!
On line 92 in vs variable i have this method function values() { return new Constructor(this, kind); }; from core-js.
I don't know what i need to do, because we need a several months (maybe year) to stay with ExtJS3 but many things in ExtJS3 not work.
EDIT
Also no one have access to ExtJS3 for make software crutch
Hard fix:
just create fix.sh file, put it in a root of project along with webpack config and put this source to fix.sh:
sed -i 's/getMethod/_getMethod/g' target/application/static/js/*.js && sed -i 's/KEYS/_KEYS/g' target/application/static/js/*.js &&
sed -i 's/VALUES/_VALUES/g' target/application/static/js/*.js &&
sed -i 's/keys/_keys/g' target/application/static/js/*.js &&
sed -i 's/values/_values/g' target/application/static/js/*.js
also replace target/application/static/js path to yours.
Add WebpackShellPlugin and in webpack add this:
plugins: [
new WebpackShellPlugin({
onBuildEnd: ['bash ./fix.sh']
})
]

Array Data to HTML Table

What is the best way to get data from an array using tabletop.js into an html table? I am trying to take the data from the array and replace the dummy data that I currently have in there. The link below better explains what I'm trying to do.
Example of Data & Table
Here is my Fiddle: https://jsfiddle.net/1qeydx4f/
HTML:
<script type="text/javascript">
var publicSpreadsheetUrl = 'https://docs.google.com/spreadsheets/d/16EypE4AkZVutLblpQEpsBu4ly7ziqBRYPxlv7wO1SJs/edit?usp=sharing';
function init() {
Tabletop.init( { key: publicSpreadsheetUrl,
callback: showInfo,
simpleSheet: true } )
}
function showInfo(data, tabletop) {
console.log(data);
}
window.addEventListener('DOMContentLoaded', init)
</script>
<div class="docs-section" id="tables">
<h6 class="docs-header">3-Pointers Made (2019)</h6>
<p> </p>
<div class="docs-example">
<table class="u-full-width">
<thead>
<tr>
<th>Name</th>
<th>Team</th>
<th>Made</th>
<th>Attempted</th>
<th>Percent</th>
</tr>
</thead>
<tbody>
<tr>
<td>Dave Gamache</td>
<td>GS</td>
<td>150</td>
<td>300</td>
<td>50%</td>
</tr>
<tr>
<td>Dwayne Johnson</td>
<td>DAL</td>
<td>128</td>
<td>298</td>
<td>43%</td>
</tr>
</tbody>
</table>
</div>
</div>
Tabletop.js:
(function() {
'use strict';
var inNodeJS = typeof process !== 'undefined' && !process.browser;
var request = function requestNotProvided() {
throw new Error("The 'request' module is only available while running in Node.");
};
if(inNodeJS) { // This will get stripped out by Uglify, and Webpack will not include it
request = require('request');
}
var supportsCORS = false;
var inLegacyIE = false;
try {
var testXHR = new XMLHttpRequest();
if (typeof testXHR.withCredentials !== 'undefined') {
supportsCORS = true;
} else {
if ('XDomainRequest' in window) {
supportsCORS = true;
inLegacyIE = true;
}
}
} catch (e) { }
// Create a simple indexOf function for support
// of older browsers. Uses native indexOf if
// available. Code similar to underscores.
// By making a separate function, instead of adding
// to the prototype, we will not break bad for loops
// in older browsers
var indexOfProto = Array.prototype.indexOf;
var ttIndexOf = function(array, item) {
var i = 0, l = array.length;
if (indexOfProto && array.indexOf === indexOfProto) {
return array.indexOf(item);
}
for (; i < l; i++) {
if (array[i] === item) {
return i;
}
}
return -1;
};
/*
Initialize with Tabletop.init( { key: '0AjAPaAU9MeLFdHUxTlJiVVRYNGRJQnRmSnQwTlpoUXc' } )
OR!
Initialize with Tabletop.init( { key: 'https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AjAPaAU9MeLFdHUxTlJiVVRYNGRJQnRmSnQwTlpoUXc&output=html&widget=true' } )
OR!
Initialize with Tabletop.init('0AjAPaAU9MeLFdHUxTlJiVVRYNGRJQnRmSnQwTlpoUXc')
*/
var Tabletop = function(options) {
// Make sure Tabletop is being used as a constructor no matter what.
if(!this || !(this instanceof Tabletop)) {
return new Tabletop(options);
}
if(typeof(options) === 'string') {
options = { key : options };
}
this.callback = options.callback;
this.wanted = options.wanted || [];
this.key = options.key;
this.simpleSheet = !!options.simpleSheet;
this.parseNumbers = !!options.parseNumbers;
this.wait = !!options.wait;
this.reverse = !!options.reverse;
this.postProcess = options.postProcess;
this.debug = !!options.debug;
this.query = options.query || '';
this.orderby = options.orderby;
this.endpoint = options.endpoint || 'https://spreadsheets.google.com';
this.singleton = !!options.singleton;
this.simpleUrl = !!(options.simpleUrl || options.simple_url); //jshint ignore:line
this.authkey = options.authkey;
this.sheetPrivacy = this.authkey ? 'private' : 'public'
this.callbackContext = options.callbackContext;
// Default to on, unless there's a proxy, in which case it's default off
this.prettyColumnNames = typeof(options.prettyColumnNames) === 'undefined' ? !options.proxy : options.prettyColumnNames;
if(typeof(options.proxy) !== 'undefined') {
// Remove trailing slash, it will break the app
this.endpoint = options.proxy.replace(/\/$/,'');
this.simpleUrl = true;
this.singleton = true;
// Let's only use CORS (straight JSON request) when
// fetching straight from Google
supportsCORS = false;
}
this.parameterize = options.parameterize || false;
if (this.singleton) {
if (typeof(Tabletop.singleton) !== 'undefined') {
this.log('WARNING! Tabletop singleton already defined');
}
Tabletop.singleton = this;
}
/* Be friendly about what you accept */
if (/key=/.test(this.key)) {
this.log('You passed an old Google Docs url as the key! Attempting to parse.');
this.key = this.key.match('key=(.*?)(&|#|$)')[1];
}
if (/pubhtml/.test(this.key)) {
this.log('You passed a new Google Spreadsheets url as the key! Attempting to parse.');
this.key = this.key.match('d\\/(.*?)\\/pubhtml')[1];
}
if(/spreadsheets\/d/.test(this.key)) {
this.log('You passed the most recent version of Google Spreadsheets url as the key! Attempting to parse.');
this.key = this.key.match('d\\/(.*?)\/')[1];
}
if (!this.key) {
this.log('You need to pass Tabletop a key!');
return;
}
this.log('Initializing with key ' + this.key);
this.models = {};
this.modelNames = [];
this.model_names = this.modelNames; //jshint ignore:line
this.baseJsonPath = '/feeds/worksheets/' + this.key + '/' + this.sheetPrivacy +'/basic?alt=';
if (inNodeJS || supportsCORS) {
this.baseJsonPath += 'json';
} else {
this.baseJsonPath += 'json-in-script';
}
if(!this.wait) {
this.fetch();
}
};
// A global storage for callbacks.
Tabletop.callbacks = {};
// Backwards compatibility.
Tabletop.init = function(options) {
return new Tabletop(options);
};
Tabletop.sheets = function() {
this.log('Times have changed! You\'ll want to use var tabletop = Tabletop.init(...); tabletop.sheets(...); instead of Tabletop.sheets(...)');
};
Tabletop.prototype = {
fetch: function(callback) {
if (typeof(callback) !== 'undefined') {
this.callback = callback;
}
this.requestData(this.baseJsonPath, this.loadSheets);
},
/*
This will call the environment appropriate request method.
In browser it will use JSON-P, in node it will use request()
*/
requestData: function(path, callback) {
this.log('Requesting', path);
if (inNodeJS) {
this.serverSideFetch(path, callback);
} else {
//CORS only works in IE8/9 across the same protocol
//You must have your server on HTTPS to talk to Google, or it'll fall back on injection
var protocol = this.endpoint.split('//').shift() || 'http';
if (supportsCORS && (!inLegacyIE || protocol === location.protocol)) {
this.xhrFetch(path, callback);
} else {
this.injectScript(path, callback);
}
}
},
/*
Use Cross-Origin XMLHttpRequest to get the data in browsers that support it.
*/
xhrFetch: function(path, callback) {
//support IE8's separate cross-domain object
var xhr = inLegacyIE ? new XDomainRequest() : new XMLHttpRequest();
xhr.open('GET', this.endpoint + path);
var self = this;
xhr.onload = function() {
var json;
try {
json = JSON.parse(xhr.responseText);
} catch (e) {
console.error(e);
}
callback.call(self, json);
};
xhr.send();
},
/*
Insert the URL into the page as a script tag. Once it's loaded the spreadsheet data
it triggers the callback. This helps you avoid cross-domain errors
http://code.google.com/apis/gdata/samples/spreadsheet_sample.html
Let's be plain-Jane and not use jQuery or anything.
*/
injectScript: function(path, callback) {
var script = document.createElement('script');
var callbackName;
if (this.singleton) {
if (callback === this.loadSheets) {
callbackName = 'Tabletop.singleton.loadSheets';
} else if (callback === this.loadSheet) {
callbackName = 'Tabletop.singleton.loadSheet';
}
} else {
var self = this;
callbackName = 'tt' + (+new Date()) + (Math.floor(Math.random()*100000));
// Create a temp callback which will get removed once it has executed,
// this allows multiple instances of Tabletop to coexist.
Tabletop.callbacks[ callbackName ] = function () {
var args = Array.prototype.slice.call( arguments, 0 );
callback.apply(self, args);
script.parentNode.removeChild(script);
delete Tabletop.callbacks[callbackName];
};
callbackName = 'Tabletop.callbacks.' + callbackName;
}
var url = path + '&callback=' + callbackName;
if (this.simpleUrl) {
// We've gone down a rabbit hole of passing injectScript the path, so let's
// just pull the sheet_id out of the path like the least efficient worker bees
if(path.indexOf('/list/') !== -1) {
script.src = this.endpoint + '/' + this.key + '-' + path.split('/')[4];
} else {
script.src = this.endpoint + '/' + this.key;
}
} else {
script.src = this.endpoint + url;
}
if (this.parameterize) {
script.src = this.parameterize + encodeURIComponent(script.src);
}
this.log('Injecting', script.src);
document.getElementsByTagName('script')[0].parentNode.appendChild(script);
},
/*
This will only run if tabletop is being run in node.js
*/
serverSideFetch: function(path, callback) {
var self = this;
this.log('Fetching', this.endpoint + path);
request({url: this.endpoint + path, json: true}, function(err, resp, body) {
if (err) {
return console.error(err);
}
callback.call(self, body);
});
},
/*
Is this a sheet you want to pull?
If { wanted: ["Sheet1"] } has been specified, only Sheet1 is imported
Pulls all sheets if none are specified
*/
isWanted: function(sheetName) {
if (this.wanted.length === 0) {
return true;
} else {
return (ttIndexOf(this.wanted, sheetName) !== -1);
}
},
/*
What gets send to the callback
if simpleSheet === true, then don't return an array of Tabletop.this.models,
only return the first one's elements
*/
data: function() {
// If the instance is being queried before the data's been fetched
// then return undefined.
if (this.modelNames.length === 0) {
return undefined;
}
if (this.simpleSheet) {
if (this.modelNames.length > 1 && this.debug) {
this.log('WARNING You have more than one sheet but are using simple sheet mode! Don\'t blame me when something goes wrong.');
}
return this.models[this.modelNames[0]].all();
} else {
return this.models;
}
},
/*
Add another sheet to the wanted list
*/
addWanted: function(sheet) {
if(ttIndexOf(this.wanted, sheet) === -1) {
this.wanted.push(sheet);
}
},
/*
Load all worksheets of the spreadsheet, turning each into a Tabletop Model.
Need to use injectScript because the worksheet view that you're working from
doesn't actually include the data. The list-based feed (/feeds/list/key..) does, though.
Calls back to loadSheet in order to get the real work done.
Used as a callback for the worksheet-based JSON
*/
loadSheets: function(data) {
var i, ilen;
var toLoad = [];
this.googleSheetName = data.feed.title.$t;
this.foundSheetNames = [];
for (i = 0, ilen = data.feed.entry.length; i < ilen ; i++) {
this.foundSheetNames.push(data.feed.entry[i].title.$t);
// Only pull in desired sheets to reduce loading
if (this.isWanted(data.feed.entry[i].content.$t)) {
var linkIdx = data.feed.entry[i].link.length-1;
var sheetId = data.feed.entry[i].link[linkIdx].href.split('/').pop();
var jsonPath = '/feeds/list/' + this.key + '/' + sheetId + '/' + this.sheetPrivacy + '/values?alt=';
if (inNodeJS || supportsCORS) {
jsonPath += 'json';
} else {
jsonPath += 'json-in-script';
}
if (this.query) {
// Query Language Reference (0.7)
jsonPath += '&tq=' + this.query;
}
if (this.orderby) {
jsonPath += '&orderby=column:' + this.orderby.toLowerCase();
}
if (this.reverse) {
jsonPath += '&reverse=true';
}
toLoad.push(jsonPath);
}
}
this.sheetsToLoad = toLoad.length;
for(i = 0, ilen = toLoad.length; i < ilen; i++) {
this.requestData(toLoad[i], this.loadSheet);
}
},
/*
Access layer for the this.models
.sheets() gets you all of the sheets
.sheets('Sheet1') gets you the sheet named Sheet1
*/
sheets: function(sheetName) {
if (typeof sheetName === 'undefined') {
return this.models;
} else {
if (typeof(this.models[sheetName]) === 'undefined') {
// alert( "Can't find " + sheetName );
return;
} else {
return this.models[sheetName];
}
}
},
sheetReady: function(model) {
this.models[model.name] = model;
if (ttIndexOf(this.modelNames, model.name) === -1) {
this.modelNames.push(model.name);
}
this.sheetsToLoad--;
if (this.sheetsToLoad === 0) {
this.doCallback();
}
},
/*
Parse a single list-based worksheet, turning it into a Tabletop Model
Used as a callback for the list-based JSON
*/
loadSheet: function(data) {
var that = this;
new Tabletop.Model({
data: data,
parseNumbers: this.parseNumbers,
postProcess: this.postProcess,
tabletop: this,
prettyColumnNames: this.prettyColumnNames,
onReady: function() {
that.sheetReady(this);
}
});
},
/*
Execute the callback upon loading! Rely on this.data() because you might
only request certain pieces of data (i.e. simpleSheet mode)
Tests this.sheetsToLoad just in case a race condition happens to show up
*/
doCallback: function() {
if(this.sheetsToLoad === 0) {
this.callback.apply(this.callbackContext || this, [this.data(), this]);
}
},
log: function() {
if(this.debug) {
if(typeof console !== 'undefined' && typeof console.log !== 'undefined') {
Function.prototype.apply.apply(console.log, [console, arguments]);
}
}
}
};
/*
Tabletop.Model stores the attribute names and parses the worksheet data
to turn it into something worthwhile
Options should be in the format { data: XXX }, with XXX being the list-based worksheet
*/
Tabletop.Model = function(options) {
var i, j, ilen, jlen;
this.columnNames = [];
this.column_names = this.columnNames; // jshint ignore:line
this.name = options.data.feed.title.$t;
this.tabletop = options.tabletop;
this.elements = [];
this.onReady = options.onReady;
this.raw = options.data; // A copy of the sheet's raw data, for accessing minutiae
if (typeof(options.data.feed.entry) === 'undefined') {
options.tabletop.log('Missing data for ' + this.name + ', make sure you didn\'t forget column headers');
this.originalColumns = [];
this.elements = [];
this.ready();
return;
}
for (var key in options.data.feed.entry[0]){
if (/^gsx/.test(key)) {
this.columnNames.push(key.replace('gsx$',''));
}
}
this.originalColumns = this.columnNames;
this.original_columns = this.originalColumns; // jshint ignore:line
for (i = 0, ilen = options.data.feed.entry.length ; i < ilen; i++) {
var source = options.data.feed.entry[i];
var element = {};
for (j = 0, jlen = this.columnNames.length; j < jlen ; j++) {
var cell = source['gsx$' + this.columnNames[j]];
if (typeof(cell) !== 'undefined') {
if (options.parseNumbers && cell.$t !== '' && !isNaN(cell.$t)) {
element[this.columnNames[j]] = +cell.$t;
} else {
element[this.columnNames[j]] = cell.$t;
}
} else {
element[this.columnNames[j]] = '';
}
}
if (element.rowNumber === undefined) {
element.rowNumber = i + 1;
}
this.elements.push(element);
}
if (options.prettyColumnNames) {
this.fetchPrettyColumns();
} else {
this.ready();
}
};
Tabletop.Model.prototype = {
/*
Returns all of the elements (rows) of the worksheet as objects
*/
all: function() {
return this.elements;
},
fetchPrettyColumns: function() {
if (!this.raw.feed.link[3]) {
return this.ready();
}
var cellurl = this.raw.feed.link[3].href.replace('/feeds/list/', '/feeds/cells/').replace('https://spreadsheets.google.com', '');
var that = this;
this.tabletop.requestData(cellurl, function(data) {
that.loadPrettyColumns(data);
});
},
beforeReady: function() {
if(this.postProcess) {
for (i = 0, ilen = this.elements.length; i < ilen; i++) {
this.postProcess(element);
}
}
},
ready: function() {
this.beforeReady();
this.onReady.call(this);
},
/*
* Store column names as an object
* with keys of Google-formatted "columnName"
* and values of human-readable "Column name"
*/
loadPrettyColumns: function(data) {
var prettyColumns = {};
var columnNames = this.columnNames;
var i = 0;
var l = columnNames.length;
for (; i < l; i++) {
if (typeof data.feed.entry[i].content.$t !== 'undefined') {
prettyColumns[columnNames[i]] = data.feed.entry[i].content.$t;
} else {
prettyColumns[columnNames[i]] = columnNames[i];
}
}
this.prettyColumns = prettyColumns;
this.pretty_columns = this.prettyColumns; // jshint ignore:line
this.prettifyElements();
this.ready();
},
/*
* Go through each row, substitutiting
* Google-formatted "columnName"
* with human-readable "Column name"
*/
prettifyElements: function() {
var prettyElements = [],
orderedPrettyNames = [],
i, j, ilen, jlen;
for (j = 0, jlen = this.columnNames.length; j < jlen ; j++) {
orderedPrettyNames.push(this.prettyColumns[this.columnNames[j]]);
}
for (i = 0, ilen = this.elements.length; i < ilen; i++) {
var newElement = {};
for (j = 0, jlen = this.columnNames.length; j < jlen ; j++) {
var newColumnName = this.prettyColumns[this.columnNames[j]];
newElement[newColumnName] = this.elements[i][this.columnNames[j]];
}
prettyElements.push(newElement);
}
this.elements = prettyElements;
this.columnNames = orderedPrettyNames;
},
/*
Return the elements as an array of arrays, instead of an array of objects
*/
toArray: function() {
var array = [],
i, j, ilen, jlen;
for (i = 0, ilen = this.elements.length; i < ilen; i++) {
var row = [];
for (j = 0, jlen = this.columnNames.length; j < jlen ; j++) {
row.push(this.elements[i][ this.columnNames[j]]);
}
array.push(row);
}
return array;
}
};
if(typeof module !== 'undefined' && module.exports) { //don't just use inNodeJS, we may be in Browserify
module.exports = Tabletop;
} else if (typeof define === 'function' && define.amd) {
define(function () {
return Tabletop;
});
} else {
window.Tabletop = Tabletop;
}
})();
This can actually be achieved pretty simply. All you need to do is give your table an ID to be able to select it, and have a loop in the tabletop callback:
function gotData(data) {
const table = document.getElementById("table1-id").tBodies[0];
for (const player of data) {
const row = table.insertRow(-1); // index -1 inserts at bottom
const keys = Object.keys(player);
for (let i = 0; i < keys.length; i++) {
const c = row.insertCell(i);
c.appendChild(document.createTextNode(player[keys[i]]));
}
}
}

(JS) Custom, inheritable, namespace to call controllers in MVC

I am currently trying to wrap my head around creating a JavaScript namespace for organizing our JS files, that can be used to access specific methods that allow calling methods from MVC controllers. My confusion revolves around namespacing and inheriting the or applying the namespace when it is called in a different source.
Namespace TEST.js
var TEST = TEST || {}; // Needed?
(function() {
if (typeof String.prototype.trimLeft !== "function") {
String.prototype.trimLeft = function () {
return this.replace(/^\s+/, "");
};
}
if (typeof String.prototype.trimRight !== "function") {
String.prototype.trimRight = function () {
return this.replace(/\s+$/, "");
};
}
if (typeof Array.prototype.map !== "function") {
Array.prototype.map = function (callback, thisArg) {
for (var i = 0, n = this.length, a = []; i < n; i++) {
if (i in this) a[i] = callback.call(thisArg, this[i]);
}
return a;
};
}
this.Settings = {
Timer: 300
};
this.Service = (name, isApi) => {
let location = isApi === true ? "~/Controller/api/" + name : "~/Controller/" + name;
this.Call = (data, method, type, callback) => {
let method = location + "/" + method + ".cs";
let data = typeof data === "object" ? data : {};
let type = type || "GET";
callback = fetch(method, {
method: type,
headers: {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then((res) => res.json())
.then((data) => console.log(data));
return callback;
};
};
this.Functions = {
PageWidth: function () {
// return parseInt main container css width
},
setCookie: function (name, value) {
var val = value + ";domain=" + window.location.host + ";path=/;";
document.cookie = name + "=" + val;
},
deleteCookie: (name) => { document.cookie = name + "=null;domain=" + window.location.host + ";path=/;expires=Thu, 01 Jan 1900 00:00:00 GMT;"; },
getCookie: (name) => { getCookies()[name]; },
getCookies: () => {
var c = document.cookie, v = 0, cookies = {};
if (document.cookie.match(/^\s*\$Version=(?:"1"|1);\s*(.*)/)) {
c = RegExp.$1;
v = 1;
}
if (v === 0) {
c.split(/[,;]/).map(function (cookie) {
var parts = cookie.split(/=/, 2),
name = decodeURIComponent(parts[0].trimLeft()),
value = parts.length > 1 ? decodeURIComponent(parts[1].trimRight()) : null;
cookies[name] = value;
});
} else {
c.match(/(?:^|\s+)([!#$%&'*+\-.0-9A-Z^`a-z|~]+)=([!#$%&'*+\-.0-9A-Z^`a-z|~]*|"(?:[\x20-\x7E\x80\xFF]|\\[\x00-\x7F])*")(?=\s*[,;]|$)/g).map(function ($0, $1) {
var name = $0,
value = $1.charAt(0) === '"'
? $1.substr(1, -1).replace(/\\(.)/g, "$1")
: $1;
cookies[name] = value;
});
}
return cookies;
},
getQSParams: (query) => {
query
? (/^[?#]/.test(query) ? query.slice(1) : query)
.split('&')
.reduce((params, param) => {
let [key, value] = param.split('=');
params[key] = value ? decodeURIComponent(value.replace(/\+/g, ' ')) : '';
return params;
}, {}
)
: {}
}
}
this.ClientState = {};
this.getWidth = function () {
return Math.max(
document.body.scrollWidth,
document.documentElement.scrollWidth,
document.body.offsetWidth,
document.documentelement.offsetWidth,
document.documentElement.clientWidth
);
}
this.getHeight = function () {
return Math.max(
document.body.scrollHeight,
document.documentElement.scrollHeight,
document.body.offsetHeight,
document.documentElement.offsetHeight,
document.documentElement.clientHeight
);
}
}).apply(ELITE); // Var up top go here instead?
And my testing code to see if this works:
<script type="text/javascript" src='<%=ResolveUrl("~/Content/Scripts/TEST.js") %>'></script>
<script type="text/javascript">
$(function () {
var test = new TEST.Service("TestController", true);
var data = {};
test.Call(data, "TestMethod", "GET", function (resp) {
console.log(resp);
});
}(TEST));
</script>
I am sure it is something simple or a mix-up of things.
Question: Correctly namespacing a JS file to be inherited by other JS files or JS script calls for calling MVC controller methods?
Bonus: Would this be better executed as a class instead? I do have access to using ES5/ES6 and of course jQuery will be minified in with this TEST.js file!

Unable to display the PDF object in IE8

I would like to request help to resolve an IE browser incompatibility issue which is facing in ASP.Net MVC application. One of the pages of the application contains a link which displays a PDF. In IE8, the page shows an error ("Internet explorer cannot display this page" or Blank page). However, i am able to access the pdf in Google Chrome, Mozilla Firefox and IE9.
Actually, I need to display PDF in IE8.
If anyone has faced a similar issue before or have any resolutions, could you please help us resolve this? i tried out a couple of options, but could not resolve it with that.
HTML
<div id="pdf1" class="message_details_pdf"></div>
Java script Code
var myPDF = new PDFObject({
url: 'my_pdf_url',
pdfOpenParams: {
view: 'Fit',
scrollbars: '0',
toolbar: '0',
statusbar: '0',
navpanes: '0'
}
}).embed("pdf1");
I faced a problem similar to yours, but I was fighting against IE11. I added some lines of code to pdfobject.js to solve my problem. I do not know if this works with IE8, but I assume my mod can help you in some way.
Search the mods by finding "//#" without quotes, in the code below. Hope this helps.
var PDFObject = function (obj)
{
if (!obj || !obj.url) { return false; }
var pdfobjectversion = "1.2",
//Set reasonable defaults
id = obj.id || false,
width = obj.width || "100%",
height = obj.height || "100%",
pdfOpenParams = obj.pdfOpenParams,
url,
pluginTypeFound;
/* ----------------------------------------------------
Supporting functions
---------------------------------------------------- */
//Tests specifically for Adobe Reader (aka Acrobat) in Internet Explorer
var hasReaderActiveX = function ()
{
var axObj = null;
if (window.ActiveXObject)
{
axObj = new ActiveXObject("AcroPDF.PDF");
//If "AcroPDF.PDF" didn't work, try "PDF.PdfCtrl"
if (!axObj) { axObj = new ActiveXObject("PDF.PdfCtrl"); }
//If either "AcroPDF.PDF" or "PDF.PdfCtrl" are found, return true
if (axObj !== null) { return true; }
}
//If you got to this point, there's no ActiveXObject for PDFs
return false;
};
//Tests specifically for Adobe Reader (aka Adobe Acrobat) in non-IE browsers
var hasReader = function ()
{
var i,
n = navigator.plugins,
count = n.length,
regx = /Adobe Reader|Adobe PDF|Acrobat/gi;
for (i = 0; i < count; i++) { if (regx.test(n[i].name)) { return true; } }
return false;
};
//Detects unbranded PDF support
var hasGeneric = function ()
{
var plugin = navigator.mimeTypes["application/pdf"];
return (plugin && plugin.enabledPlugin);
};
//# ===============================================
//# taken from http://www.quirksmode.org/js/detect.html
//# ===============================================
var BrowserDetect = {
init: function () {
this.browser = this.searchString(this.dataBrowser) || "Other";
this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "Unknown";
},
searchString: function (data) {
for (var i = 0; i < data.length; i++) {
var dataString = data[i].string;
this.versionSearchString = data[i].subString;
if (dataString.indexOf(data[i].subString) !== -1) {
return data[i].identity;
}
}
},
searchVersion: function (dataString) {
var index = dataString.indexOf(this.versionSearchString);
if (index === -1) {
return;
}
var rv = dataString.indexOf("rv:");
if (this.versionSearchString === "Trident" && rv !== -1) {
return parseFloat(dataString.substring(rv + 3));
} else {
return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
}
},
dataBrowser: [{string: navigator.userAgent,subString: "Chrome",identity: "Chrome"}, {string: navigator.userAgent,subString: "MSIE",identity: "Explorer"}, {string: navigator.userAgent,subString: "Trident",identity: "Explorer"}, {string: navigator.userAgent,subString: "Firefox",identity: "Firefox"}, {string: navigator.userAgent,subString: "Safari",identity: "Safari"}, {string: navigator.userAgent,subString: "Opera",identity: "Opera"}]
};
//# END===============================================
//Determines what kind of PDF support is available: Adobe or generic
var pluginFound = function ()
{
var type = null;
var versione = null;
//# ===============================================
//# Start browser detecting
//# ===============================================
BrowserDetect.init();
if (hasReader() || hasReaderActiveX())
{
type = "Adobe";
version = null;
} else if (hasGeneric())
{
type = "generic";
version = null;
//# ===============================================
//# ...check if explorer
//# ===============================================
} else if (BrowserDetect.browser == 'Explorer')
{
type = "IE";
version = BrowserDetect.version;
}
return {'type': type,'version': version};
};
//If setting PDF to fill page, need to handle some CSS first
var setCssForFullWindowPdf = function ()
{
var html = document.getElementsByTagName("html");
if (!html) { return false; }
var html_style = html[0].style,
body_style = document.body.style;
html_style.height = "100%";
html_style.overflow = "hidden";
body_style.margin = "0";
body_style.padding = "0";
body_style.height = "100%";
body_style.overflow = "hidden";
};
//Creating a querystring for using PDF Open parameters when embedding PDF
var buildQueryString = function (pdfParams)
{
var string = "",
prop;
if (!pdfParams) { return string; }
for (prop in pdfParams) {
if (pdfParams.hasOwnProperty(prop)) {
string += prop + "=";
if (prop === "search") {
string += encodeURI(pdfParams[prop]);
} else {
string += pdfParams[prop];
}
string += "&";
}
}
//Remove last ampersand
return string.slice(0, string.length - 1);
};
//Simple function for returning values from PDFObject
var get = function (prop)
{
var value = null;
switch (prop) {
case "url":
value = url;
break;
case "id":
value = id;
break;
case "width":
value = width;
break;
case "height":
value = height;
break;
case "pdfOpenParams":
value = pdfOpenParams;
break;
case "pluginTypeFound":
value = pluginTypeFound;
break;
case "pdfobjectversion":
value = pdfobjectversion;
break;
}
return value;
};
/* ----------------------------------------------------
PDF Embedding functions
---------------------------------------------------- */
var embed = function (targetID)
{
if (!pluginTypeFound) { return false; }
var targetNode = null;
if (targetID)
{
//Allow users to pass an element OR an element's ID
targetNode = (targetID.nodeType && targetID.nodeType === 1) ? targetID : document.getElementById(targetID);
//Ensure target element is found in document before continuing
if (!targetNode) {
return false;
}
} else
{
targetNode = document.body;
setCssForFullWindowPdf();
width = "100%";
height = "100%";
}
//# ===============================================
//# ...and, if explorer found, write an iframe instead of an object
//# ===============================================
if (pluginTypeFound == 'IE')
{
targetNode.innerHTML = '<iframe type="application/pdf" width="' + width + '" height="' + height + '" src="' + url + '"><p>nineoclick</p></iframe>';
} else
{
targetNode.innerHTML = '<object data="' + url + '" type="application/pdf" width="' + width + '" height="' + height + '" style="z-index:800 !important;"></object>';
}
return targetNode.getElementsByTagName("object")[0];
};
//The hash (#) prevents odd behavior in Windows
//Append optional Adobe params for opening document
url = encodeURI(obj.url) + "#" + buildQueryString(pdfOpenParams);
plugin = pluginFound();
pluginTypeFound = plugin.type;
pluginVersionFound = plugin.version;
this.get = function (prop) {
return get(prop);
};
this.embed = function (id) {
return embed(id);
};
return this;
};

PhantomJS -- Scraping data feed -- Some AJAX content not loading, even with generous setTimeout

I have a generic PhantomJS setup for scraping feeds (we are doing this with owner's permission, for a client) -- you give it a URL, jQuery/javascript code for turning the page, and a selector to select links from the feed.
This feed seems to be loading everything fine except for the buttons to turn the page [see images].
Rendered by PhantomJS:
Rendered by Chrome on my computer:
I have been stumped for over a day.
Any help much appreciated.
My code:
var page = new WebPage({
settings: {
loadPlugins: true,
userAgent : "Mozilla/5.0 (X11; Linux i686) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46 Safari/536.5",
XSSAuditingEnabled: false,
webSecurityEnabled: false
},
viewportSize: { width: 1366, height: 768 }
}),
output_phantom = {errors: [], results: null};
var turn_page_jquery = "$('#yui-pg0-0-next-link').click_link()",
url_selector_jquery = "$('h3 a').multiAttr('href')",
url = "http://www.springcjd.com/new/search?dpt=2#QryString=%3FlogSearch%3Dfalse%26sortCol%3Dnull%26sortType%3Dnull%26VIN%3Dnull%26dealerStockID%3Dnull%26stockType%3D2%26year%3Dnull%26make%3Dnull%26model%3Dnull%26subModel%3Dnull%26body%3Dnull%26minMileage%3Dnull%26maxMileage%3Dnull%26numOfDoors%3Dnull%26certified%3Dnull%26minDFList%3Dnull%26maxDFList%3Dnull%26onLotAfter%3Dnull%26onLotBefore%3Dnull%26pageNum%3D1%26carsPerPage%3D30%26fullText%3Dnull%26%26mpghmn%3Dnull%26%26lotID%3Dnull%26daysOnLotMin%3Dnull%26%26output%3Djson%22";
// Start things going here
get_links_from_pages(url, url_selector_jquery, turn_page_jquery);
// Allows you to pass args to function in page
function evaluate(page, func) {
var args = [].slice.call(arguments, 2);
var fn = "function() { return (" + func.toString() + ").apply(this, " + JSON.stringify(args) + ");}";
return page.evaluate(fn);
}
page.onError = function (msg, trace) {
console.log(msg);
trace.forEach(function(item) {
console.log(' ', item.file, ':', item.line);
});
};
// Communicator between phantomJS and the page.
page.onConsoleMessage = function(msg)
{
var msg_json = JSON.parse(msg);
if(msg_json && msg_json.type)
{
var type = msg_json.type;
var message = msg_json.message;
switch(type)
{
case 'return_value':
output_phantom.results = message;
console.log(JSON.stringify(output_phantom));
phantom.exit();
break;
case 'message':
output_phantom.errors.push(message);
break;
case 'exit':
phantom.exit();
break;
case 'render':
var photo_name = 'phantom_test.png';
if(message != '')
photo_name = message;
page.render(photo_name);
break;
}
}
else
output_phantom.errors.push(msg);
};
function inject_scripts()
{
// Inject jquery and our additional script if they don't exist
// Would like to be able to overwrite an older version of jQuery
if(page.evaluate(function () { return typeof jQuery;}) == 'undefined')
{
if(page.evaluate(function () { return typeof $;}) == 'function') {
console.log("'$' symbol already used.");
}
else
{
if (!page.injectJs("/../../jquery.js")) {
console.log("jQuery not loaded...");
phantom.exit();
}
}
}
// Inject scripts that allow communication using fn onConsoleMessage
if (!page.injectJs("/../lf_additional.js")) {
console.log("Additional scripts not loaded...");
phantom.exit();
}
}
function run_phantom(url, fn/* args here, just not seen */)
{
var extra_args = [].slice.call(arguments, 2);
page.open(url, function (status) {
// if (status !== 'success') {
// console.log('Unable to load the url! (URL: '+url+')');
// phantom.exit();
// }
// else
// {
inject_scripts();
output_phantom = {errors: [], results: null};
// run our js code inside the headless browser.
extra_args.unshift(page, fn);
evaluate.apply(this, extra_args);
// }
});
}
function get_links_from_pages(url, url_selector_jquery, turn_page_jquery)
{
var fn = function(url_selector_jquery, turn_page_jquery)
{
var results = [];
var i = 0;
var interval = setInterval(function()
{
// Photograph page right before selecting values
phantom_render('ph_scjd_'+i+'.png');
var selected_data = eval(url_selector_jquery);
//
results.push(selected_data);
// Try to turn the page
eval(turn_page_jquery);
// Get the first 4 pages
if(i >= 3) {
phantom_return(results);
clearInterval(interval);
}
i++;
}, 3000);
};
return run_phantom(url, fn, url_selector_jquery, turn_page_jquery);
}
//////////////////////////////////////////////////////////
// Other stuff
// Improved json parsing
(function() {
var parse = JSON.parse;
JSON = {
stringify: JSON.stringify,
validate: function(str) {
try {
parse(str);
return true;
} catch(err){
return err;
}
},
parse: function(str) {
try {
return parse(str);
} catch(err){
return undefined;
}
}
}
})();
The injected file 'additional.js':
/*
* These are additional scripts intended to make selection of multiple elements
* much more concise.
*/
$.fn.click_link = function() {
simulateMouseClick(this.selector);
};
$.fn.collect = function(fn) {
var values = [];
if (typeof fn == 'string') {
var prop = fn;
fn = function() { return this.attr(prop); };
}
$(this).each(function() {
var val = fn.call($(this));
values.push(val);
});
return values;
};
$.fn.multiAttr = function(attrName) {
return this.collect(attrName);
};
// .text() should be pretty close, except concatenated?
$.fn.multiHtml = function() {
var val_array = this.collect(function() { return this.html(); });
return val_array;
};
$.fn.multiVal = function() {
return this.multiAttr('value');
};
// The commented out code is much more concise, but probably less efficient
// $(arr1).not(arr2).length == 0 && $(arr2).not(arr1).length == 0
jQuery.extend({
compareArray: function (arrayA, arrayB) {
if (arrayA.length != arrayB.length) { return false; }
// sort modifies original array
// (which are passed by reference to our method!)
// so clone the arrays before sorting
var a = jQuery.extend(true, [], arrayA);
var b = jQuery.extend(true, [], arrayB);
a.sort();
b.sort();
for (var i = 0, l = a.length; i < l; i++) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
});
function simulateMouseClick(selector) {
var targets = document.querySelectorAll(selector),
evt = document.createEvent('MouseEvents'),
i, len;
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
for ( i = 0, len = targets.length; i < len; ++i ) {
targets[i].dispatchEvent(evt);
}
}
function send_console_command(type, message)
{
var msg = {};
if(!message) message = '';
msg.message = message;
msg.type = type;
msg.validation = 'phantom_js_communicator';
console.log(JSON.stringify(msg));
}
function phantom_exit() {
send_console_command('exit');
}
function phantom_message(msg) {
send_console_command('message', msg);
}
function phantom_return(return_val) {
send_console_command('return_value', return_val);
}
function phantom_render(photo_name) {
send_console_command('render', photo_name);
}
Isn't it:
var page = require('webpage').create();
page.viewportSize = { width: 1366, height: 768 };
Untested, just reading the docs.

Categories

Resources