console.log (dict) will give you
{"click here:":{"message":"点击这里"},"apply":{"message":"应用"},"a translation test!":{"message":"js翻译示例!"},"tabLanding":"欢迎","tabSetup":{"message":"安装"}}
I want tabSetup appear like 安装 in html
here is the html code:
<li class="tab_setup"></li>
what i see is it does not shows correctly just showed as [object Object]
it should showed as 安装
here is my java-script. Thanks
var dict = {};
var systemLang = navigator.language.toLowerCase().slice(0,2);
$(function () {
registerWords();
switch(getCookieVal("lang")) {
case "en" :
setLanguage("en");
break
case "zh" :
setLanguage("zh");
break
default:
setLanguage(systemLang);
}
console.log (dict);
console.log(JSON.stringify(dict));
// 切换语言事件
$("#enBtn").bind("click", function () {
setLanguage("en");
});
$("#zhBtn").bind("click", function () {
setLanguage("zh");
});
// $("#applyBtn").bind("click", function () {
// alert(__tr("a translation test!"));
// });
});
function setLanguage(lang) {
setCookie("lang=" + lang + "; path=/;");
translate(lang);
}
function getCookieVal(name) {
var items = document.cookie.split(";");
for (var i in items) {
var cookie = $.trim(items[i]);
var eqIdx = cookie.indexOf("=");
var key = cookie.substring(0, eqIdx);
if (name == $.trim(key)) {
return $.trim(cookie.substring(eqIdx + 1));
}
}
return null;
}
function setCookie(cookie) {
var Days = 30; //此 cookie 将被保存 30 天
var exp = new Date(); //new Date("December 31, 9998");
exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
document.cookie = cookie+ ";expires=" + exp.toGMTString();
}
function translate(lang) {
if(sessionStorage.getItem(lang + "Data") != null){
dict = JSON.parse(sessionStorage.getItem(lang + "Data"));
}else{
loadDict();
}
$("[i18n]").each(function () {
switch (this.tagName.toLowerCase()) {
case "input":
$(this).val(__tr($(this).attr("i18n")));
break;
default:
$(this).text(__tr($(this).attr("i18n")));
}
});
}
function __tr(src) {
return (dict[src] || src);
}
function loadDict() {
var lang = (getCookieVal("lang") || "en");
$.ajax({
async: false,
type: "GET",
url: "/lang/"+lang + ".json",
success: function (msg) {
dict = msg;
sessionStorage.setItem(lang + 'Data', JSON.stringify(dict));
}
});
}
// 遍历所有lang属性的标签赋值
function registerWords() {
$('[i18n]:not(.i18n-replaced').each(function() {
var element = $(this);
element.html(translate(element.attr('i18n')));
element.addClass('i18n-replaced');
});
}
It works if json file like "tabSetup": "Set up". .It does not works if json file like "tabSetup": { "message": "Set up" }
function __tr has error, repair like this
function __tr(src) {
return (dict[src].message || src);
}
Related
For the life of me I cannot see the suttle difference between copied code. The _getMiscData method in a child widget apparently doesn't exist according to the parent widget. Can someone explain this?
I tried different method names in case I was using a reserved word. I tried private and public method with same result.
$(function() {
$.widget("custom.textquestion", $.custom.base, {
_create: function() {
this.element.data("_getControlValue", this.getControlValue());
},
getControlValue: function() {
this.element.attr("usersanswer", this.getResponseJSON());
},
_getAnswerSelection: function(answer) {
var qname = this._getQuestionName();
var type = this.getType();
return '<div class="radio span6"><label><input type="text" class="answerfield" name="optradio-' + qname + '" value="' + answer.answertext + '"></label></div>'
},
_getAnswersDiv: function(answers) {
// DIV is required for wrapping around list of answers
// so that they can be added all at once.
var answerdivs = '<div class="answerlist">'
for (k = 0; k < answers.length; k++) {
answerdivs += this._getAnswerSelection(answers[k]);
}
answerdivs += '</div>';
return answerdivs;
},
_getPopulatedEditor: function(answers) {
var editanswerdiv = "";
for (p = 0; p < answers.length; p++) {
editanswerdiv += '<label>Default</label><input type="text" onblur="savequestiondata()" identifier="' + answers[p].answerid + '" name="editanswer' + this._getQuestionName(this.options.questioncontrol) + '" size="20" value="' + answers[p].answertext + '"/><br/>'
}
return editanswerdiv;
},
_getAnswersJSON: function(div) {
var answers = [];
$(div).find("input[name='editanswer" + this._getQuestionName(this.options.questioncontrol) + "']").each(function(i, u) {
var answer = {
answerid: $(this).attr('identifier'),
answertext: $(this).val(),
answerorder: 0,
rating: 0
};
answers.push(answer);
});
return answers;
},
_setAnswerJSON: function(answer) {
answer = answer.replace(/['"]+/g, '');
this.options.questioncontrol.find("input[name='optradio-" + this._getQuestionName() + "']").val(answer);
return true;
},
getResponseJSON: function() {
qname = this._getQuestionName();
console.log("The control name is " + qname);
var answer = this.options.questioncontrol.find("input[name='optradio-" + qname + "']").val();
console.log("The answer is " + answer);
return answer;
},
_refresh: function() {
qname = this._getQuestionName(this.options.questioncontrol);
// Create the divs for the answer block, then
// append to this question as the list of answers.
var answers = this._getStoredData().data.answers;
var answerhtml = this._getAnswersDiv(answers);
this.options.questioncontrol.find(".answer-list").html("");
this.options.questioncontrol.find(".answer-list").append(answerhtml);
// Get the explanation text and add to control.
var explanation = this._getStoredData().data.explanation;
this.options.questioncontrol.find(".explanation").text(explanation);
// Populate the editor controls with the answers that
// are already stored - ready for editing.
var editanswerhtml = this._getPopulatedEditor(answers);
this.options.questioncontrol.find(".editanswers").html("");
this.options.questioncontrol.find(".editanswers").append(editanswerhtml);
this.options.questioncontrol.find(".notes").text(explanation);
},
_getQuestionText: function(div) {
var qtext;
$(div).find("input[name='questiontextedit']").each(function() {
qtext = $(this).val();
});
return qtext;
},
_getMiscData: function() {
var info = [this.options.questioncontrol.find(".email-mask").val()];
return info;
},
_setOtherData: function(info) {
if (info.emailmask == "true")
this.options.questioncontrol.find(".email-mask").attr("checked", "checked");
else
this.options.questioncontrol.find(".email-mask").attr("checked", "");
},
_getExplanationText: function(div) {
var etext = $(div).find(".notes").val();
return etext;
}
});
});
$(function() {
$.widget("custom.base", {
// default options
options: {
questioncontrol: this,
questiondata: null,
_storedData: [],
},
_create: function() {
},
_refresh: function() {
},
getEditedAnswers: function(div) {
// Get the set of answers that were edited.
if (!div)
div = this.options.questioncontrol;
var answersresult = this._getAnswersJSON(div);
var question = this._getQuestionText(div);
var typename = this.getType();
var qname = this._getQuestionName(this.options.questioncontrol);
var pagenumber = this._getStoredData(qname).data.pagenumber;
var order = this._getStoredData(qname).data.order;
var explanation = this._getExplanationText(div);
var otherdata = this._getMiscData();
var result = {
title: question,
type: typename,
pageid: pagenumber,
qname: qname,
answers: answersresult,
questionorder: order,
explanation: explanation,
otherdata: otherdata
};
return result;
},
getType: function() {
return $(this.options.questioncontrol).attr('id');
},
setData: function(questiondata) {
// Set the title for the question. I.e, the text
// for the question.
this.options.questioncontrol.find(".questiontitle").text(questiondata.title);
this.options.questioncontrol.find("input[name='questiontextedit']").val(questiondata.title);
this.options.questioncontrol.find(".notes").text(questiondata.explanation);
// Store the data into datastore.
var stored = 0;
if (this._getStoredData(questiondata.qname) == null) {
this.options._storedData.push({
qname: questiondata.qname,
data: questiondata
});
} else {
var datastored = this._getStoredData(questiondata.qname);
datastored.data = questiondata;
}
if (questiondata.otherdata)
this._setOtherData(questiondata.otherdata);
this._refresh();
},
setAnswer: function(answer) {
this._setAnswerJSON(answer);
},
_getQuestionName: function() {
return this.options.questioncontrol.find('.questionname').val();
},
_getStoredData: function() {
var qname = this._getQuestionName(this.options.questioncontrol);
for (p = 0; p < this.options._storedData.length; p++) {
if (this.options._storedData[p].qname == qname)
return this.options._storedData[p];
}
return null;
},
});
});
The custom.base widget shouldn't return with "this.getMiscData is not a function"
Not sure why my code is not working because the code I took from below is working in JSFiddle here
String.prototype.interpolate = (function() {
var re = /\[(.+?)\]/g;
return function(o) {
return this.replace(re, function(_, k) {
return o[k];
});
}
}());
var _obj = {
hey: 'Hey',
what: 'world',
when: 'today'
}
document.write(
'[hey]-hey, I saved the [what] [when]!'.interpolate(_obj)
);
But my code below doesn't seem to be doing the same thing. It still has the bracket values [NAME][ADDRESS][PHONE] and not the replaced data values:
$(document).ready(function () {
$('#goSearching').click(function () {
var isNumber = $.isNumeric($('#searchBox').val());
var theSearch = $('#searchBox').val();
var theURL = '';
if (isNumber) {
if (theSearch.length >= 10) {
//Search by NPI#
$('#titleOfSearchResult').html('P search results by NPI #:');
theURL = 'http://zzzzz.com:151/P/GetNPI/';
} else {
//Search by P #
$('#titleOfSearchResult').html('P search results by P #:');
theURL = 'http://zzzzzz.com:151/P/GetNo/';
}
} else {
//Search by P Name
$('#titleOfSearchResult').html('P search results by P Name:');
theURL = 'http://zzzzz.com:151/P/PName/';
}
$.ajax({
url : theURL + $('#searchBox').val() + '/',
type : 'GET',
dataType : 'xml',
timeout : 10000,
cache : false,
crossDomain : true,
success : function (xmlResults) {
console.log(xmlResults);
var _htmlObj = {};
$(xmlResults).find("P").each(function() {
_htmlObj = {
NAME : $(this).find("pName").text(),
ADDRESS : $(this).find("pSpecialty").text(),
PHONE : $(this).find("pUserid").text()
}
console.log($(this).find("pName").text());
console.log($(this).find("pSpecialty").text());
console.log($(this).find("pUserid").text());
$("#theResults").append(
'<p><strong>[NAME]</strong></p>' +
'<p>[ADDRESS]</p>' +
'<p>[PHONE]</p>' +
'<p> </p>'.interpolate(_htmlObj)
);
});
},
error : function(jqXHR, textStatus) {
console.log("error: " + textStatus);
}
});
});
String.prototype.interpolate = (function () {
var re = /\[(.+?)\]/g;
return function (o) {
return this.replace(re, function (_, k) {
return o[k];
});
}
}());
});
In the console it outputs the correct returned values but it won't replace those values with the placeholders [NAME][ADDRESS][PHONE].
Any help to fix this issue would be great! Thanks!
You're only calling interpolate on the last string
'<p><strong>[NAME]</strong></p>' +
'<p>[ADDRESS]</p>' +
'<p>[PHONE]</p>' +
'<p> </p>'.interpolate(_htmlObj)
Member access has a higher precedence than addition, so it needs to be:
('<p><strong>[NAME]</strong></p>' +
'<p>[ADDRESS]</p>' +
'<p>[PHONE]</p>' +
'<p> </p>').interpolate(_htmlObj)
Example from #TrueBlueAussie: jsfiddle.net/TrueBlueAussie/fFSYA/9
I'm trying to make an XML based menu with JavaScript, XML and jQuery. I've been successful at getting the categories of the menu, but haven't been able to generate the items in the categories.
My script is as follows, and later in this thread, I've asked for suggestions for this code:
var animalsXMLurl = 'http://dl.dropboxusercontent.com/u/27854284/Stuff/Online/XML_animals.xml';
$(function() {
$.ajax({
url: animalsXMLurl, // name of file you want to parse
dataType: "xml",
success: function parse(xmlResponse) {
var data = $("item", xmlResponse).map(function() {
return {
id: $("animal_id", this).text(),
title: $("animal_title", this).text(),
url: $("animal_url", this).text(),
category: $("animal_category", this).text().split('/'),
};
}).get();
var first_item = category_gen(data, 0);
$('ul.w-nav-list.level_2').append(first_item);
var categnumber = new Array();
for (i = 1; i <= data.length; i++) //for splitting id, and getting 0 for category_number (1 or 2 or 3...and so on)
{
categnumber[i] = data[i].id.split('_');
console.log(categnumber[i][0]);
for (j = 1; j <= data.length; j++) //appending via a function.
{
var data_text = category_or_animal(data, categnumber, j);
console.log(data_text);
$('ul.w-nav-list.level_2').append(data_text);
}
}
function category_or_animal(d, catg, k) {
var catg1 = new Array();
var catg2 = new Array();
var catg1 = d[k].id.split('_');
if (d[k - 1]) {
var catg2 = d[k - 1].id.split('_');
//if(d[k-1].id)
if (catg1[0] != catg2[0])
return category_gen(d, k);
} else
return '</ul>' + animal_gen(d, k);
}
function category_gen(d, z) {
var category_var = '<li class="w-nav-item level_2 has_sublevel"><a class="w-nav-anchor level_2" href="javascript:void(0);"><span class="w-nav-title">' + d[z].category + '</span><span class="w-nav-arrow"></span></a><ul class="w-nav-list level_3">';
return category_var;
}
function animal_gen(d, z) {
var animal_var = '<li class="w-nav-item level_3"><a class="w-nav-anchor level_3" href="animals/' + d[z].url + '"><span class="w-nav-title">' + d[z].title + '</span><span class="w-nav-arrow"></span></a></li>';
return animal_var;
}
}, error: function() {
console.log('Error: Animals info xml could not be loaded.');
}
});
});
Here's the JSFiddle link for the above code: http://jsfiddle.net/mohitk117/d7XmQ/4/
In the above code I need some alterations, with which I think the code might work, so I'm asking for suggestions:
Here's the function that's calling separate functions with arguments to generate the menu in above code:
function category_or_animal(d, catg, k) {
var catg1 = new Array();
var catg2 = new Array();
var catg1 = d[k].id.split('_');
if (d[k - 1]) {
var catg2 = d[k - 1].id.split('_');
//if(d[k-1].id)
if (catg1[0] != catg2[0])
return category_gen(d, k);
} else
return animal_gen(d, k) + '</ul>';
}
At the if(catg1[0] != catg2[0]) it checks if the split string 1_2 or 1_3 is equal to 1_1 or 1_2 respectively. By split, I mean the first element: 1 .... if you have a look at the xml: [ :: Animals XML :: ], you'll see that the animal_id is in the format of %category_number% _ %item_number% ... So I need to create the menu with CATEGORY > ITEM (item=animal name)
Now if I could return category_gen() + animal() with animal(){ in a for loop for all the matching category id numbers} then maybe this could be complete! But I don't of a count script for conditioning the for loop (i=0;i<=count();i++)...
Would anyone know of how to get this script functioning?
Hard to tell what the provided JSFiddle is trying to do.
This is my best stab at it. I used JQuery to parse the XML out into categories and generate lists of items.
http://jsfiddle.net/d7XmQ/8/
"use strict";
var animalsXMLurl = 'http://dl.dropboxusercontent.com/u/27854284/Stuff/Online/XML_animals.xml';
$(function () {
var $menu = $('#menu');
$.ajax({
url: animalsXMLurl, // name of file you want to parse
dataType: "xml",
success: handleResponse,
error: function () {
console.log('Error: Animals info xml could not be loaded.');
}
});
function handleResponse(xmlResponse) {
var $data = parseResponse(xmlResponse);
createMenu($data);
}
function parseResponse(xmlResponse) {
return $("item", xmlResponse).map(function () {
var $this = $(this);
return {
id: $this.find("animal_id").text(),
title: $this.find("animal_title").text(),
url: $this.find("animal_url").text(),
category: $this.find("animal_category").text()
};
});
}
function createMenu($data) {
var categories = {};
$data.each(function (i, dataItem) {
if (typeof categories[dataItem.category] === 'undefined') {
categories[dataItem.category] = [];
}
categories[dataItem.category].push(dataItem);
});
$.each(categories, function (category, categoryItems) {
var categoryItems = categories[category];
$menu.append($('<h2>').text(category));
$menu.append(createList(categoryItems));
});
}
function createList(categoryItems) {
var $list = $('<ul>');
$.each(categoryItems, function (i, dataItem) {
$list.append(createItem(dataItem));
});
return $list;
}
function createItem(dataItem) {
return $('<li>').text(dataItem.title);
}
});
You can solve this without using any for/while loop or forEach.
function myCounter(inputWords) {
return inputWords.reduce( (countWords, word) => {
countWords[word] = ++countWords[word] || 1;
return countWords;
}, {});
}
Hope it helps you!
I'm using this autocomplete code to be able to pull stock information:
var YAHOO = {};
YAHOO.util = {};
YAHOO.util.ScriptNodeDataSource = {};
var stockSymbol;
var compName;
YUI({
filter: "raw"
}).use("datasource", "autocomplete", "highlight", function (Y) {
var oDS, acNode = Y.one("#ac-input");
oDS = new Y.DataSource.Get({
source: "http://d.yimg.com/aq/autoc?query=",
generateRequestCallback: function (id) {
YAHOO.util.ScriptNodeDataSource.callbacks =
YUI.Env.DataSource.callbacks[id];
return "&callback=YAHOO.util.ScriptNodeDataSource.callbacks";
}
});
oDS.plug(Y.Plugin.DataSourceJSONSchema, {
schema: {
resultListLocator: "ResultSet.Result",
resultFields: ["symbol", "name", "exch", "type", "exchDisp"]
}
});
acNode.plug(Y.Plugin.AutoComplete, {
maxResults: 10,
resultTextLocator: "symbol",
resultFormatter: function (query, results) {
return Y.Array.map(results, function (result) {
var asset = result.raw,
text = asset.symbol +
" " + asset.name +
" (" + asset.type +
" - " + asset.exchDisp + ")";
return Y.Highlight.all(text, query);
});
},
requestTemplate: "{query}®ion=US&lang=en-US",
source: oDS
});
acNode.ac.on("select", function (e) {
alert(e.result.raw.name);
stockSymbol = e.result.raw.symbol;
compName = e.result.raw.name;
alert("stockSymbol is "+stockSymbol);
alert("compName is "+compName);
});
});
I have a text field where the text is being entered, then I need to display a few pieces of information based on what was entered:
$(document).ready(function(e) {
//$(".selector").button({icons: {primary: "ui-icon-search"}});
//$(".home").button({icons: {primary: "ui-icon-home"}});
var q = window.location.href.split("?ac-input=");
alert("q is "+q)
if (q && q[1])
$("input").val(q[1]);
alert("what is this?" +q[1]);
runForm();
});
..........
function runForm(){
$("#stock_news").html("");
//var stockSymbol = e.result.raw.symbol;
alert('stockSymbol in runForm is ' +stockSymbol);
alert('compname is runForm is '+compName);
var newsStocks = "http://query.yahooapis.com/v1/public/yql?.......";
$.getJSON(newsStocks, function(data) {
var headlines = data.query.results.a;
newStr = "<h3>Current Headlines</h3>";
newStr += "<ol>";
for(var i=0; i<headlines.length; ++i){
var news = headlines[i];
newStr += "<li><a href='"+news.href+"'>"+news.content+"</a></li>";
}
newStr += "</ol>";
$("#stock_news").html(newStr);
});
htmlStr = '<img src="http://chart.finance.yahoo.com/z?s='+stockSymbol+'&t=5d&q=l&l=off&z=s®ion=US&lang=en-EN"/>';
$("#stock_graph").html(htmlStr);
}
What is happening is, the stockSymbol and compName are correctly set from entering, but for some reason nothing renders on the page, as q is undefined....Any ideas on where I am messing up here?
Figured it out. I needed to call runForm inside the acNode.ac.on("select", function (e)
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.