I need to create an email, attach another email message to it and save it into drafts folder;
To proceed, I use first GetItem, then CreateItem.
But each time it appears 2 email messages in that folder.
Each email message contains the attachment and is in draft mode. I don't understand why there is 2 email messages.
Please help me. Thank you.
Here is my code:
(function () {
"use strict";
Office.initialize = function (reason) {
$(document).ready(function () {
app.initialize();
$('#fowardToGroups').click(function () { sendNow(); });
});
};
var item_id;
var mailbox;
async function sendNow() {
var item = Office.context.mailbox.item;
item_id = item.itemId;
mailbox = Office.context.mailbox;
var receiver="test#ymail.com";
var soapToCreateItem='<?xml version="1.0" encoding="utf-8"?>'+
' <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'+
' xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"'+
' xmlns:xsd="http://www.w3.org/2001/XMLSchema"' +
' xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"'+
' xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'+
' <soap:Header>'+
' <t:RequestServerVersion Version="Exchange2013" xmlns="http://schemas.microsoft.com/exchange/services/2006/types" soap:mustUnderstand="0" />'+
' </soap:Header>'+
' <soap:Body>'+
' <m:CreateItem MessageDisposition="SaveOnly">'+
' <m:SavedItemFolderId> '+
' <t:DistinguishedFolderId Id="drafts" /> '+
' </m:SavedItemFolderId> '+
' <m:Items>'+
' <t:Message>'+
' <t:Subject>Suspicious e-mail </t:Subject>'+
' <t:Body BodyType="HTML">body</t:Body>'+
' <t:ToRecipients>'+
' <t:Mailbox>'+
' <t:EmailAddress>'+receiver+'</t:EmailAddress>'+
' </t:Mailbox>'+
' </t:ToRecipients>'+
' </t:Message>'+
' </m:Items>'+
' </m:CreateItem>'+
' </soap:Body>'+
' </soap:Envelope>';
mailbox.makeEwsRequestAsync(soapToCreateItem, soapToCreateItemCallback);
}
function soapToCreateItemCallback(asyncResult) {
var parser;
var xmlDoc;
if (asyncResult.error != null) {
app.showNotification("EWS Status 1", asyncResult.error.message);
}
else {
var response = asyncResult.value;
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(response, "text/xml");
}
else // Older Versions of Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(response);
}
var result = xmlDoc.getElementsByTagName("m:ResponseCode")[0].textContent;
if (result == "NoError") {
app.showNotification("Status", "Success !");
}
else {
app.showNotification("Status", "error : " + result);
}
}
}
})();
Related
I am developing a new web addin for Outlook using EWS and JavaScript. The scope is to get the current email selected and add it to a new email as attachement. Following the instructions found here: https://msdn.microsoft.com/en-us/library/office/dn726694(v=exchg.150).aspx#bk_createattachews -> I have created some functions to do those steps explained in the MSDN documentation. The problem is that I don't get any errors or something that can tell me what I am doing wrong. Here is my Code:
function soapToForwardItemCallback(asyncResult) {
var parser;
var xmlDoc;
if (asyncResult.error != null) {
app.showNotification("EWS Status", asyncResult.error.message);
}
else {
var response = asyncResult.value;
if (window.DOMParser) {
parser = new DOMParser();
xmlDoc = parser.parseFromString(response, "text/xml");
}
else // Older Versions of Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(response);
}
// Get the required response, and if it's NoError then all has succeeded, so tell the user.
// Otherwise, tell them what the problem was. (E.G. Recipient email addresses might have been
// entered incorrectly --- try it and see for yourself what happens!!)
var result = xmlDoc.getElementsByTagName("m:ResponseCode")[0].textContent;
if (result == "NoError") {
app.showNotification("EWS Status", "Success!");
}
else {
app.showNotification("EWS Status", "The following error code was recieved: " + result);
}
}
}
function getCurrentEmail() {
var item = Office.context.mailbox.item;
item_id = item.itemId;
var getMimeContent = '<?xml version="1.0" encoding="utf-8"?>' +
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' +
'xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"' +
'xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"' +
'xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
// ' <soap:Header>' +
// ' <RequestServerVersion Version="Exchange2013" xmlns="http://schemas.microsoft.com/exchange/services/2006/types" soap:mustUnderstand="0" />' +
// ' </soap:Header>' +
'<soap:Body>' +
'<m:GetItem>' +
// ' xmlns="http://schemas.microsoft.com/exchange/services/2006/messages"' +
// ' xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">' +
'<m:ItemShape>' +
'<t:BaseShape>IdOnly</t:BaseShape>' +
'<t:AdditionalProperties>' +
'<t:FieldURI FieldURI="item:MimeContent" />' +
'<t:FieldURI FieldURI="item:Subject" />' +
'</t:AdditionalProperties>' +
'</m:ItemShape>' +
'<m:ItemIds>' +
'<t:ItemId Id="' + item_id + '"/>' +
'</m:ItemIds>' +
'</m:GetItem>' +
'</soap:Body>' +
'</soap:Envelope>'
mailbox.makeEwsRequestAsync(getMimeContent, createMail);
}
function createMail(asyncResult) {
var parser = new DOMParser();
var xmlDoc;
if (asyncResult.error !== null) {
app.showNotification("EWS Status", asyncResult.error.message);
}
else {
var response = asyncResult.value;
if (window.DOMParser) {
xmlDoc = parser.parseFromString(response, "text/xml");
}
else // Older Versions of Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(response);
}
var toAddresses = 'alexandru.banica#rodacsoft.ro';
var addressesSoap = "";
addressesSoap += "<t:Mailbox><t:EmailAddress>" + toAddresses + "</t:EmailAddress></t:Mailbox>";
var soapToCreateNewEmail = '<?xml version="1.0" encoding="utf-8"?>'+
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'+
'xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"'+
'xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"'+
' xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'+
' <soap:Header>'+
' <t:RequestServerVersion Version="Exchange2013" />'+
' </soap:Header>'+
' <soap:Body>'+
' <m:CreateItem MessageDisposition="SaveOnly">'+
' <m:Items>'+
' <t:Message>'+
' <t:Subject>Message with Item Attachment (MimeContent)</t:Subject>'+
' <t:Body BodyType="HTML">The attachmen</t:Body>'+
' <t:ToRecipients>'+ addressesSoap
+
' </t:ToRecipients>'+
' </t:Message>'+
' </m:Items>'+
' </m:CreateItem>'+
' </soap:Body>'+
' </soap:Envelope>'
mailbox.makeEwsRequestAsync(soapToCreateNewEmail,soapToGetItemDataCallback);
}
}
function createAttachement(asyncResult) {
var parser = new DOMParser();
var xmlDoc;
if (asyncResult.error !== null) {
app.showNotification("EWS Status", asyncResult.error.message);
}
else {
var response = asyncResult.value;
if (window.DOMParser) {
xmlDoc = parser.parseFromString(response, "text/xml");
}
else // Older Versions of Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(response);
}
var mimeTag = xmlDoc.getElementsByTagName("t:MimeContent")[0].innerText;
var soapToCreateAttachement = '<?xml version="1.0" encoding="utf-8"?>'+
' <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'+
' xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"'+
' xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"'+
' xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'+
' <soap:Header>'+
' <t:RequestServerVersion Version="Exchange2013" />'+
' </soap:Header>'+
' <soap:Body>'+
' <m:CreateAttachment>'+
' <m:ParentItemId Id="'+item_id+'" />'+
' <m:Attachments>'+
' <t:ItemAttachment>'+
' <t:Name>Play tennis?</t:Name>'+
' <t:IsInline>false</t:IsInline>'+
' <t:Message>'+
' <t:MimeContent CharacterSet="UTF-8">'+ mimeTag +'</t:MimeContent>'+
' </t:Message>'+
' </t:ItemAttachment>'+
' </m:Attachments>'+
' </m:CreateAttachment>'+
' </soap:Body>'+
' </soap:Envelope>'
mailbox.makeEwsRequestAsync(soapToCreateAttachement,sendEmailAsAttachement);
}
}
function sendEmailAsAttachement(asyncResult) {
var parser = new DOMParser();
var xmlDoc;
if (asyncResult.error !== null) {
app.showNotification("EWS Status", asyncResult.error.message);
}
else {
var response = asyncResult.value;
if (window.DOMParser) {
xmlDoc = parser.parseFromString(response, "text/xml");
}
else // Older Versions of Internet Explorer
{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = false;
xmlDoc.loadXML(response);
}
var changeKey = xmlDoc.getElementsByTagName("t:ItemId")[0].getAttribute("ChangeKey");
var soapToSendEmailAttachment = ' <?xml version="1.0" encoding="utf-8"?>' +
' <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' +
' xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"' +
' xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"' +
' xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
' <soap:Header>' +
' <t:RequestServerVersion Version="Exchange2013" />' +
' </soap:Header>' +
' <soap:Body>' +
' <m:SendItem SaveItemToFolder="true">' +
' <m:ItemIds>' +
' <t:ItemId Id="'+ item_id +'"' +
' ChangeKey="'+ changeKey +'" />' +
' </m:ItemIds>' +
' <m:SavedItemFolderId>' +
' <t:DistinguishedFolderId Id="sentitems" />' +
' </m:SavedItemFolderId>' +
' </m:SendItem>' +
' </soap:Body>' +
' </soap:Envelope>'
mailbox.makeEwsRequestAsync(soapToSendEmailAttachment, soapToForwardItemCallback);
}
}
The first function called on button click is getCurrentEmail(). I am not sure if I can do the SOAP calls like that. Any help would be greatly appreciated! Please tell me if you need additional information. Thank you!
I am not sure if I can do the SOAP calls like that.
The following resource describes EWS operations that add-ins support. "m:CreateAttachment" is not one of them; probably you should start from there.
EDIT:
I don't understand how comes you don't get any errors. Are you debugging? Can you hit break point? Well this is all weird.
Now let me tell you what I've done and what issues with your code I noticed ...
I created the simple project and added your code. I called "getCurrentEmail()" function and work just with this function. I didn't verify any other function, because I believe you should do this on your own.
Javascript errors: If you use "strict" JS mode (and you should!) the function has "item_id" variable which is not defined as "var". You should make it local by using "var" keyword. Next when you call "mailbox.makeEwsRequestAsync" the "mailbox" variable is undefined as well. you should call it as "Office.context.mailbox.makeEwsRequestAsync".
EWS request is not properly formed at all. I don't know, may be you played with it, but the example EWS XML from the resource you have provided is different than you are creating by inserting message Id. When I fixed JS errors (look at the point 2 above) and send EWS request it returned starts "Error" and proper description that request is misformed. I have changed the request to match the request provided in example and it returns "success" and information you have requested, as of subject and MIME content.
I will share my code just for the function you have asked and the rest try to do on your own. Here you go ...
function _wrapSoapEnvelope(payload) {
var result = '<?xml version="1.0" encoding="utf-8"?>' +
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' +
'xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" ' +
'xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" ' +
'xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">' +
'<soap:Header>' +
'<t:RequestServerVersion Version="Exchange2013" xmlns="http://schemas.microsoft.com/exchange/services/2006/types" soap:mustUnderstand="0" />' +
'</soap:Header>' +
'<soap:Body>' + payload + '</soap:Body>' +
'</soap:Envelope>';
return result;
};
function getCurrentEmail() {
var item = Office.context.mailbox.item,
item_id = item.itemId;
var getMimeContent = '<m:GetItem>' +
'<m:ItemShape>' +
'<t:BaseShape>IdOnly</t:BaseShape>' +
'<t:AdditionalProperties>' +
'<t:FieldURI FieldURI="item:MimeContent" />' +
'<t:FieldURI FieldURI="item:Subject" />' +
'</t:AdditionalProperties>' +
'</m:ItemShape>' +
'<m:ItemIds>' +
'<t:ItemId Id="' + item_id + '"/>' +
'</m:ItemIds>' +
'</m:GetItem>'
Office.context.mailbox.makeEwsRequestAsync(_wrapSoapEnvelope(getMimeContent), createMail);
}
I've the following code:
function query1() {
var defered = Q.defer();
console.log("In query1");
var connection = mysql.createConnection({
host: '........',
user: 'm...c....a.....i',
password: '......Z....9...K',
database: '.....ol'
});
connection.connect(function(err) {
if (!err) {
console.log("Database is connected ...");
} else {
console.log("Error connecting database ...");
}
});
sql = '' +
'select c.ID as CENA_ID, ' +
' c.I_KEY as CENA_NUMERO, ' +
' c.NM_CENA as CENA_NOME, ' +
' b.DS_MAC as MAC_BOX, ' +
' v.DS_CLIENTID as ALEXA_ID, ' +
' v.FK_ID_GRUPO as GRUPO_ID ' +
' from TB_DISPOSITIVOS_VOZ v ' +
' inner join TB_GRUPOS g ' +
' on g.ID = v.FK_ID_GRUPO ' +
' inner join TB_CENAS c ' +
' on g.ID = c.FK_ID_GRUPO ' +
' inner join TB_CENTRAIS b ' +
' on g.ID = b.FK_ID_GRUPO ' +
'where v.DS_CLIENTID = "' + userId + '" ' +
'and lower(c.NM_CENA) like "%' + sceneName.toLowerCase() + '%"';
console.log("Created query");
try{
connection.query(sql, function(erro, rows, fields) {
if (!erro) {
console.log("Executed query verifying the userId");
contador = 0;
if (rows.length > 0) {
cena_id = rows[0].CENA_ID;
cena_numero = rows[0].CENA_NUMERO;
cena_nome = rows[0].CENA_NOME;
alexa_id = rows[0].ALEXA_ID;
grupo_id = rows[0].GRUPO_ID;
mac_box = rows[0].MAC_BOX;
contador = contador + 1;
}
console.log("contador: " + contador);
} else {
console.log("Error - getting the Alexa register in database" + erro);
context.fail("Error - getting the Alexa register in database" + erro);
}
});
}catch (ex){
console.log("exception: " + ex);
}
}
And this code as well:
Q.all([query1()]).then(function(results) {
console.log("Q.all log function");
if (contador > 0) {
console.log("contador > 0");
var client = mqtt.connect('mqtt://.............com');
console.log("connected to MQTT broker");
var buffer = [26,
0,0,0,0,555,645,0,0,0,0,0,
0,5555,2,Math.floor((Math.random() * 200) + 1),
0,0,0,333,13,4,0,1,0,
cena_numero
];
console.log("Created buffer");
client.on('connect', function() {
client.publish('n/c/' + mac_box + '/app', buffer);
console.log("sent MQTT");
});
speechOutput = "Command " + sceneName + " executed successfully";
repromptText = "";
console.log("Process executed successfully")
} else {
console.log("contador <= 0");
speechOutput = "This command was not found!";
repromptText = "";
}
}, function (reason) {
console.log("reason: " + reason);
});
How can I do for the second code execute only if the first query1() executed correctly? Because in the function query1() i've a MySQL Query, and I only can continue with the process after the result of this query.
Anyone can help me?
Thanks a lot!
You're missing some key concepts regarding callbacks and asynchronous behavior in Node.js. You're using the "Q" library (btw I'd recommend trying bluebird instead) to handle promises, but your "query1" function does not return a promise. That's why query1 executes but your "Q.all log function" will execute before query1 is finished.
You can structure your code like this instead (I'll give an example with bluebird since I'm more familiar with it):
var Promise = require('bluebird');
var _connection;
function query1() {
return new Promise(resolve, reject) {
//open your connection
connection.open(function (err, connection) {
if (err) return reject(err);
_connection = connection;
//do your query
_connection.query(sql, [params], function (err, data) {
if (err) return reject(err);
else resolve(data);
});
});
});
}
function query2(data) {
return new Promise(resolve, reject) {
//do your query, using data passed in from query1
_connection.query(sql, [params], function (err, data) {
if (err) return reject(err);
else resolve(data);
});
});
}
query1
.then(function (data) { query2(data); })
.catch(function (err) {
console.log('error:', err);
});
Also, just FYI, concatenating SQL string like this is a no-no that will open you up to a SQL injection attack:
like "%' + sceneName.toLowerCase() + '%"
Instead, use like "%?%" and call your SQL with connection.query(sql, [sceneName], function(err, data) {}). Hope this helps.
I solved my problem with asyncpackage like this:
var async = require('async');
async.series([
function(callback) {
//action 1...
},
function(callback){
//action 2...
}
], function(err) {
if (err) {
speechOutput = "Scene not found!";
repromptText = "Please try again.";
}
console.log("Before speechOutput");
callback(sessionAttributes,
buildSpeechletResponse(cardTitle, speechOutput, repromptText, shouldEndSession));
});
Beaglebone black - not receiving data on serial. I have connected Tx and Rx pins of the serial ports 1 and 2 directly (tx - rx). I'm kind of new to beaglebone. I used this code to send data on the serial to another device, it worked properly for transmission, but not for Rx.
I haven't found the file ttyO1, just ttyO2.
var b = require('bonescript');
var rxport = '/dev/ttyO1';
var txport = '/dev/ttyO2';
var options = { baudrate: 115200, parity: 'even', parser:
b.serialParsers.readline('\n') };
var teststring = "This is the string I'm sending out as a test";
b.serialOpen(rxport, options, onRxSerial);
function onRxSerial(x) {
console.log('rx.eventrx= ' + x.event);
if(x.err) throw('***FAIL*** ' + JSON.stringify(x));
if(x.event == 'open') {
//readReapeatedly();
b.serialOpen(txport, options, onTxSerial);
}
if(x.event == 'data') {
console.log("I am receiving on rxport");
console.log('rx (' + x.data.length +
') = ' + x.data.toString('ascii'));
}
}
function onTxSerial(x) {
console.log('tx.event = ' + x.event);
if(x.err) throw('***FAIL*** ' + JSON.stringify(x));
if(x.event == 'open') {
writeRepeatedly();
}
if(x.event == 'data') {
console.log('tx (' + x.data.length +
') = ' + x.data.toString('ascii'));
console.log(x.data);
}
}
function printJSON(x) {
console.log(JSON.stringify(x));
}
function writeRepeatedly() {
console.log("write to serial");
b.serialWrite(txport, teststring, onSerialWrite);
console.log("I have sent data");
}
function onSerialWrite(x) {
console.log("Iam in the onSerialWrite function");
if(x.err) console.log('onSerialWrite err = ' + x.err);
if(x.event == 'callback') {setTimeout(writeRepeatedly, 5000);
console.log("HERE");
}
}
i have this code that fill ListView by xml file.
when i press on one item in the ListView i go to page2.
how to pass the Fname, Lname , Phone ..... variables for the person that i pick in the ListView to page2 ?
<script>
var ALL;
var ID, Fname, Lname, Phone, Car;
function XX() {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "DD.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
$("#ZIBI").empty();
var x = xmlDoc.getElementsByTagName("men");
for (i = 0; i < x.length; i++) {
try{ID = x[i].getElementsByTagName("ID")[0].childNodes[0].nodeValue;}
catch (err) { ID = "0";}
try{Fname = x[i].getElementsByTagName("Fname")[0].childNodes[0].nodeValue;}
catch (err) { Fname = "0"; }
try{Lname = x[i].getElementsByTagName("Lname")[0].childNodes[0].nodeValue;}
catch (err) { Lname = "0"; }
try{Phone = x[i].getElementsByTagName("S_phone")[0].childNodes[0].nodeValue;}
catch (err) { Phone = "0"; }
try { Car = x[i].getElementsByTagName("car")[0].childNodes[0].nodeValue; }
catch (err) { Car = "0"; }
ALL =
'<li>' +
'<a href="page2.html" data-transition="slidedown">' +
//'<a href="tel:' + Phone + ' data-icon="location">' +
'<img src="PIC/' + ID + '.jpeg">' +
'<p class="nam">' + Fname + " " + Lname + '</p>' +
'<p class="phn">' + Phone + '</p>' +
'<p class="crr">' + Car + '</p>' +
'</a>' +
'<a href="tel:' + Phone + ' data-icon="location" ></a>' +
'</li>'
$("#ZIBI").append(ALL);
$("#ZIBI").listview("refresh");
}
}
</script>
In the new page you can use the following:
var fullname = $(this).find('p.nam').text();
var phone = $(this).find('p.phn').text();
var car = $(this).find('p.crr').text();
within the click handler for the link clicked.
However, if you have turned off ajax navigation, the above would not work.
$(document).on('click', 'li a', function() {
//catch them here
});
I happened to write a program to use the google translate (http://www.translate.google.com)
using PhantomJS.
But I'am unable to insert text into the textarea . .I’ve searched a lot but nothing proved useful . However i am able to print the result content .
Here's my code:
var page = require('webpage').create();
page.open("http://translate.google.com", function(status) {
if ( status === "success" ) {
console.log(status);
page.includeJs("//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js", function() {
var c=page.evaluate(function(){$('source').val("sample text");
return $('#source').text();
});
var f= page.evaluate(function() {
$('#source').val("sbjbsdfsdfbbs");
return $('#source').text();
});
console.log(f);//should print input text
var result= page.evaluate(function() {
$('#source').val("sbjbsdfsdfbbs");
return $('#result_box').text();
});
console.log(result);
phantom.exit()
});
}
});
Try to attach your text and languages to the URL when opening the page:
'http://translate.google.com/#en/es/translate this'
var page = require('webpage').create();
var inputText = 'translate this';
var langFrom = 'en';
var langTo = 'es';
var pageURL = 'http://translate.google.com/#' + langFrom + '/' + langTo + '/' + inputText;
page.open(pageURL, function(status) {
// your code to get results here
});
Here you go:
translate.js:
#!/usr/bin/env phantomjs
var system = require('system');
var text = system.stdin.read();
var sourceLang="en";
var targetLang="pt_BR";
var url = "https://translate.google.com/#"+sourceLang+"/"+targetLang;
var page = require('webpage').create();
page.settings.userAgent = 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:13.0) Gecko/20100101 Firefox/13.0';
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'));
};
page.onConsoleMessage = function (msg) {
if ( msg == "phanthom.exit()" ) {
phantom.exit();
} else {
system.stdout.write(msg);
system.stdout.flush();
}
page.render("test.png");
};
/*
* This function wraps WebPage.evaluate, and offers the possibility to pass
* parameters into the webpage function. The PhantomJS issue is here:
*
* http://code.google.com/p/phantomjs/issues/detail?id=132
*
* This is from comment #43.
*/
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.open(url, function (status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
var result = evaluate(page, function(text){
var getResult=function(){
var result_box=document.querySelector("#result_box");
var input_box=document.querySelector("#source");
if ( input_box == null )
setTimeout( getResult, 1000 );
else {
input_box.value=text;
if ( result_box == null || result_box.innerText == "" ) {
setTimeout( getResult, 1000 );
} else {
console.log(result_box.innerText);
console.log("phanthom.exit()")
}
}
}
getResult();
}, text );
}
});
...
$ echo "phantomjs, is a fantastic tool" | phantomjs translate.js | iconv --from cp1252
PhantomJS, é uma ferramenta fantástica