Async functions within typeaheadjs - javascript

This function works within typeahead.js context,
i use lodash request-promise and cheerio
to grab/parse/organize my data.
console.log shows every variables as it should be.
but with this line :
return '<p>' + img + data.name + ' - ' + getProviders(data) + '</p>'
i get the following error:
Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
I'm not sure what's happening, this might have something to do with typeahead.js trying to happend an invalid (because incomplete yet) DOM element.
PS: let img = $(selector).attr('src'); is intended (it stores the src attribute as a string)
PS2: if i ommit img it works:
return '<p>' + data.name + ' - ' + getProviders(data) + </p>'
function(data) {
let imgProviders = _.keys(data.url).map((r) => {
return {[r]: data.url[r]};
});
let url = imgProviders[0][_.keys(imgProviders[0])[0]].replace(/\/$/, '');
let selector = _.find(sites, {
providerName: _.keys(imgProviders[0])[0]
}).coverIMG;
let body = request.get(url, (err, res, html) => {
$ = cheerio.load(html);
// the variable that is messing with me
let img = $(selector).attr('src');
// works fine when console.log()
console.log(img, data.name, getProviders(data));
return '<p>' + img + data.name + ' - ' + getProviders(data) + '</p>';
});
}

Related

Passing a string with quotes inside of it from API response as argument to a function in JS

I'm passing below data that i'm capturing from an API to the function addToList().
//...
onclick="addToList(\'' + value.id + '\',\'' + value.title + '\',\'' value.image_url + '\')"
//...
function addTolist (id, title, image_url)
{
var data = {};
data.id = id;
data.title = title;
data.image_url = image_url;
data.format = "json";
$.ajax({
//...
}
My problem is that certain titles do have quotes in it (e.g A Knight's Tale) and i'm getting a syntax error because of it.
Is there a way to change the value that I'm capturing from value.title in order for it to be accepted as argument to my addToList function?
Thanks

Finding meta “description” using Javascript

I was trying to pass a tab object tabout in order to find the description and title of the webpage.
When I was debugging the code with some breakpoints, it was returning value, but when I am running it, it's not returning the description.
Is there any problem with the code?
function computeDescription(tabout)
{
var code = 'var meta = document.querySelector("meta[name=\'description\']");' +
'if (meta) meta = meta.getAttribute("content");' +
'({' +
' title: document.title,' +
' description: meta || ""' +
'});';
var desc;
var message = document.querySelector('#message');
chrome.tabs.executeScript(tabout.id,{code: code}, function(results) {
if (chrome.extension.lastError) {
message.innerText = 'There was an error injecting script :\n'+chrome.extension.lastError.message;
}
if (!results) {
return;
}
var result = results[0];
// Now, do something with result.title and result.description
console.log(result.title);
console.log(result.description);
desc=result.description;
});
return desc;
}
It looks like you're assuming that the callback you give to executeScript will execute before computeDescription returns. This is not true; executeScript executes asynchronously and your callback will never run before computeDescription returns.
In order to handle this, you need to to adopt the asynchronous model for your definition of computeDescription. Rather than returning a value, take a callback argument and call it when data is ready.
function computeDescription(tabout, callback) {
var code = 'var meta = document.querySelector("meta[name=\'description\']");' +
'if (meta) meta = meta.getAttribute("content");' +
'({' +
' title: document.title,' +
' description: meta || ""' +
'});';
var message = document.querySelector('#message');
chrome.tabs.executeScript(tabout.id, {code: code}, function(results) {
if (chrome.extension.lastError) {
message.innerText = 'There was an error injecting script :\n'+chrome.extension.lastError.message;
}
if (!results) {
callback();
}
callback(results[0].description);
});
}
Then your usage similarly transforms from
console.log('Le description is: ' + computeDescription(tab));
to
computeDescription(tab, function(description) {
console.log('Le description is: ' + description);
});

push function with javascript doesn't work in this place

var members = ['herpaderpus', 'turtles_head', 'nubstep_rs', 'ardens_fide', 'newending', 'pve_bros', 'rsphilippe', 'pureismwars', 'smap51', 'iprimal_rs', 'im_mr_bloo', 'mrknowles100', 'aikohero', 'cowsbelieve', 'dombo_12', 'diovista', 'mrpixels17'];
var memberData = [];
$.each(members, function(index, member) {
$.getJSON('https://api.twitch.tv/kraken/users/' + member + '?callback=?', function(d) {
if(d.status == 404) {}
else {
var data = [];
data[0] = member;
data[1] = d.display_name;
memberData.push(data[0]);
$.getJSON('https://api.twitch.tv/kraken/streams/' + data[0] + '?callback=?', function(d) {
if(d.stream != null) {
$( "#player" ).append( "<img src='http://pso-clan.com/twitch/lib/images/online.png'>" + "<a target='_blank' href='http://www.twitch.tv/" + data[0] + "'>" + data[1] + "</a>" + " - Viewers: " + d.stream.viewers + "<br>" );
}
else {
$( "#offline" ).append( "<img src='http://pso-clan.com/twitch/lib/images/offline.png'>" + "<a target='_blank' href='http://www.twitch.tv/" + data[0] + "'>" + data[1] + "</a> - Offline<br>" );
}
});
}
});
}); alert(memberData[0]);
I don't seem to be able to call
memberData.push(data[0]);
in the place where it's right now, the alert just show undefined. Why doesn't it properly push the member to the memberData array?
You're actually incorrect - where you're using .push() is just fine (in the callback of your first $.getJSON() request).
Where you're alerting it, however is not, because this is an asynchronous request, whereby the alert occurs before the first ajax request is complete.
Take a look at the console output here: http://jsfiddle.net/remus/spSxE/ -- you'll see that undefined appears before any of the array push logging.
Options:
Rewrite your method to use parallel ajax requests like the solution here
Write the necessary DOM update functions (or whatever you're doing with the results) into the callback of each ajax request so that it is updated after each call completes.

how to ignore errors in phantomjs

I have a web crawler and I use phantomjs to parse pages,
I want to get the html, but I always get this type of errors in the output before the html code
ReferenceError: Can't find variable: collapse_content_selector
http://staticloads.com/js/toggle.js?v=2013.10.04:135
TypeError: 'undefined' is not a function (evaluating '$('[placeholder]').placeholderLabel()')
how can I stop that
The easiest way is to add an error handler to phantom.onerror or webpage.onerror.
These callbacks are invoked when there is a JavaScript execution error (in the page or in your script).
page.onError = function(msg, trace) {
var msgStack = ['ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
});
}
// uncomment to log into the console
// console.error(msgStack.join('\n'));
};

"Cannot find function replace" errror when trying to replace part of a string

I need a way to replace part of a string with another string using Google Apps Script. I tested the following and it worked:
function test(){
var value = 'https://plus.google.com/117520727894266469000';
var googleimageURL = googlePlus(value);
Logger.log('Returned Result: ' + googleimageURL);
}
function googlePlus(value){
var apiKey = ScriptProperties.getProperty('apiKey');
var re = 'http://'
var theURL = value;
Logger.log('Google+ is called: ' + value);
var replacingItem = 'https://';
var theURL = theURL.replace(re, replacingItem);
Logger.log('Google+ Values 2: ' + value + ' : ' + theURL + ' after ' + replacingItem);
return imageURL;
}
But, when I embedded into the following code, it did not work. Any idea?
//If a Google+ column was not specified,put a flag.
if (googleColumn && column == googleColumn) {
if (value == ""){
columns.push(nogoogleColumn);
values.push(flag);
var googleimageURL="";
} else {
var googleimageURL = googlePlus(value);
Logger.log('Returned Result: ' + googleimageURL);
}
}
The script did not work as I wish. It seems to stop at line:
var theURL = theURL.replace(re, replacingItem);
Additional information: Google notified me with the following message
onFormSubmit
TypeError: Cannot find function replace in object https://plus.google.com/117520727894266469000. (line 536) formSubmit
I found the mistake. It is Type Error. value in the second block is not a "string", while the first block is a "string". Hence to fix the second block, I need to use:
var value = value.toString();
before passing to googlePlus(value)

Categories