How to add onmessage handler for strophe muc plugin - handler

How to add on-message handler for strophe MUC plugin.
Currently i added callback function for join action.
Gab.connection.muc.join(room_name+"#muc.162.242.222.249", login_id,
function(message){

You can check message types in your general message handler:
connection.addHandler(onMessage, null, 'message', null, null, null);
...
function onMessage(msg) {
var to = msg.getAttribute('to');
var from = msg.getAttribute('from');
var type = msg.getAttribute('type');
var elems = msg.getElementsByTagName('body');
if (type == "chat" && elems.length > 0) {
var body = elems[0];
console.log('CHAT: I got a message from ' + from + ': ' + Strophe.getText(body));
} else if (type == "groupchat" && elems.length > 0) {
var body = elems[0];
var room = Strophe.unescapeNode(Strophe.getNodeFromJid(from));
var nick = Strophe.getResourceFromJid(from);
console.log('GROUP CHAT: I got a message from ' + nick + ': ' + Strophe.getText(body) + ' in room: ' + room);
}
// we must return true to keep the handler alive.
// returning false would remove it after it finishes.
return true;
}

Related

Python selenium close modal window after reading its content

I have the HTML as following:
function showModal(msg) {
var content = document.getElementById("modal-content");
content.innerHTML = msg;
modal.style.display = "block";
}
showModal(msg + "<br>Job started, check status on the project jobs page.");
After all is said and done, I get the following window:
How do I read the content of the box and if there is "Success" I can click the close on top right to go back to the previous page.
I don't have a clue how to approach this.
Edit: Extended HTML looks as following:
function makeInputScenario(ids,params,has_extra = false) {
var sd = gete("sdate").value;
var ed = gete("edate").value;
var sdt = new Date(sd);
var edt = new Date(ed);
if (sdt > edt) {
showModal("Start date is after end date, please fix!");
return;
}
var p = gete("pool").value;
var dzr = gete("dzr").value;
var pfd = gete("pfd").value;
var udb = gete("udb").value;
var uds = gete("uds").value;
if (uds == "None") uds = "";
var rop = gete("rop-text").value;
var fuds = gete("fuds").value;
if (fuds == "None") fuds = "";
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", function() {
hideProgress();
if (!params) setInteraction(false);
if (xhr.status == 200) {
var msg = "<strong>SUCCESS:</strong><br><pre>" + xhr.responseText + "</pre>"
showModal(msg);
if (params) {
if (has_extra) {
showProgress("Processing, please wait...");
doAction("run-params","POST","/scenario/run","user=PJMRTO LONG RUN AUCTION" + params + "&cir=" + getCir(),function (ret) {
setInteraction(false);
clearTimeout(updProgrs);
showModal(msg + "<p>" + ret + "</p>");
});
} else {
var ods = gete("ods").value;
showProgress("Adding new job, please wait...");
doAction("run-params","POST","/job","user=PJMRTO LONG RUN AUCTION&sdate=" + sd + "&edate=" + ed + "&ids=" + ids + "&ods=" + ods + "&rops=" + encode(rop) + "&post=" + encode("") + "&std=" + encode("") + "&cir=" + getCir(),function (job) {
showProgress("Starting job " + job + ", please wait...");
doAction("run-params","POST","/run","id=" + job + params,function (x) {
setInteraction(false);
clearTimeout(updProgrs);
showModal(msg + "<br>Job started, check status on the project jobs page.");
});
});
}
}
} else if (xhr.status == 500) {
setInteraction(false);
clearTimeout(updProgrs);
var logurl = "/idblog?q=host&name=" + encode(ids) + "&pool=" + encode(p) + "&sd=" + encode(sd) + "&ed=" + encode(ed);
showModal(wrapError("<pre>" + xhr.responseText + "</pre><br><button onclick=\"getIDBlog('" + logurl + "');\" class=\"btn btn-primary\">Download Log</button>"));
}
},false);
setInteraction(true);
if (params) {
gete("start-job").style.display = "none";
gete("host-status").style.display = "none";
}
var sparams = "user=PJMRTO LONG RUN AUCTION&pool=" + p + "&dzr=" + dzr + "&pfd=" + pfd + "&ids=" + ids + "&sdate=" + sd + "&edate=" + ed + "&udb=" + udb + "&uds=" + uds + "&rop=" + encode(rop);
if (fuds != "") {
sparams += "&fuds=" + fuds + "&ius=" + gete("ods").value;
showProgress("Creating base and fixed UC input scenarios, please wait...");
} else {
showProgress("Creating input scenario, please wait...");
}
updProgrs = setTimeout(updateProgress, 300000);
xhr.open("POST","/scenario",true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("x-csrf-token","NhISQUB1eCANGh46HwsgTnsAISkCAAAATeFn4B0myInXzZc7+8QJMA==");
xhr.send(sparams);
}
So here variable "msg" is storing the value "SUCCESS". It would be better to get the variable "msg" usin javascript.
So that would be :-
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://Reachyourpage")
message = driver.execute_script("return msg")
print ("SUCCESS" in message)
It should return true in case of success. I am no expert in Python but just a beginner so mind my coding.. !!
C# equivalant here would be :-
IJavaScriptExecutor js = (IJavaScriptExecutor)_driver;
string title = js.ExecuteScript("return msg");
Here, title will have the complete message.
The algorithm is to get the value of "msg" var using javascript.
For Closing the message, have u tried using SendKeys(Keys.Esc) ??
Hope it Helps!!

Loading webpage incompletely Phantomjs

I have problems capturing and loading the webpage:
https://myaccount.nytimes.com/auth/login
The username and password fields as well as the submit button are missing. What could be the reason? Thanks
As you can see the code listed below waits for each and all the resources to be loaded, one by one.
I did not write the code, however it is excellent and tested by many. The original can be found here:
https://gist.github.com/cjoudrey/1341747
(ALL the credits to the guy who wrote it.)
var resourceWait = 3000,
maxRenderWait = 30000,
url = 'https://myaccount.nytimes.com/auth/login'; //'https://twitter.com/#!/nodejs';
var page = require('webpage').create(),
count = 0,
forcedRenderTimeout,
renderTimeout;
page.viewportSize = { width: 1280, height : 1024 };
function doRender() {
page.render('twitter.png');
phantom.exit();
}
page.onResourceRequested = function (req) {
count += 1;
console.log('> ' + req.id + ' - ' + req.url);
clearTimeout(renderTimeout);
};
page.onResourceReceived = function (res) {
if (!res.stage || res.stage === 'end') {
count -= 1;
console.log(res.id + ' ' + res.status + ' - ' + res.url);
if (count === 0) {
renderTimeout = setTimeout(doRender, resourceWait);
}
}
};
page.open(url, function (status) {
if (status !== "success") {
console.log('Unable to load url');
phantom.exit();
} else {
forcedRenderTimeout = setTimeout(function () {
console.log(count);
doRender();
}, maxRenderWait);
}
});

AdWord Script Export to BigQuery "Empty Response"

Utilizing the following AdWords Script to export to BigQuery, the BigQuery.Jobs.insert is causing the script to terminate due to "Empty response". Any reason the call is not getting a response?
var ACCOUNTS = ['xxx','xxx'];
var CONFIG = {
BIGQUERY_PROJECT_ID: 'xxx',
BIGQUERY_DATASET_ID: 'xxx',
// Truncate existing data, otherwise will append.
TRUNCATE_EXISTING_DATASET: true,
TRUNCATE_EXISTING_TABLES: true,
// Back up reports to Google Drive.
WRITE_DATA_TO_DRIVE: false,
// Folder to put all the intermediate files.
DRIVE_FOLDER: 'Adwords Big Query Test',
// Default date range over which statistics fields are retrieved.
DEFAULT_DATE_RANGE: '20140101,20140105',
// Lists of reports and fields to retrieve from AdWords.
REPORTS: [{NAME: 'KEYWORDS_PERFORMANCE_REPORT',
CONDITIONS: 'WHERE Impressions>0',
FIELDS: {'AccountDescriptiveName' : 'STRING',
'Date' : 'STRING',
'CampaignId' : 'STRING',
'CampaignName' : 'STRING',
'AdGroupId' : 'STRING',
'AdGroupName' : 'STRING',
'Id' : 'STRING',
'Criteria' : 'STRING',
'KeywordMatchType' : 'STRING',
'AdNetworkType1' : 'STRING',
'AdNetworkType2' : 'STRING',
'Device' : 'STRING',
'AveragePosition' : 'STRING',
'QualityScore' : 'STRING',
'CpcBid' : 'STRING',
'TopOfPageCpc' : 'STRING',
'Impressions' : 'STRING',
'Clicks' : 'STRING',
'ConvertedClicks' : 'STRING',
'Cost' : 'STRING',
'Conversions' : 'STRING'
}
}],
RECIPIENT_EMAILS: [
'xxx',
]
};
function main() {
createDataset();
for (var i = 0; i < CONFIG.REPORTS.length; i++) {
var reportConfig = CONFIG.REPORTS[i];
createTable(reportConfig);
}
folder = getDriveFolder();
// Get an account iterator.
var accountIterator = MccApp.accounts().withIds(ACCOUNTS).withLimit(10).get();
var jobIdMap = {};
while (accountIterator.hasNext()) {
// Get the current account.
var account = accountIterator.next();
// Select the child account.
MccApp.select(account);
// Run reports against child account.
var accountJobIds = processReports(folder, account.getCustomerId());
jobIdMap[account.getCustomerId()] = accountJobIds;
}
waitTillJobsComplete(jobIdMap);
sendEmail(jobIdMap);
}
function createDataset() {
if (datasetExists()) {
if (CONFIG.TRUNCATE_EXISTING_DATASET) {
BigQuery.Datasets.remove(CONFIG.BIGQUERY_PROJECT_ID,
CONFIG.BIGQUERY_DATASET_ID, {'deleteContents' : true});
Logger.log('Truncated dataset.');
} else {
Logger.log('Dataset %s already exists. Will not recreate.',
CONFIG.BIGQUERY_DATASET_ID);
return;
}
}
// Create new dataset.
var dataSet = BigQuery.newDataset();
dataSet.friendlyName = CONFIG.BIGQUERY_DATASET_ID;
dataSet.datasetReference = BigQuery.newDatasetReference();
dataSet.datasetReference.projectId = CONFIG.BIGQUERY_PROJECT_ID;
dataSet.datasetReference.datasetId = CONFIG.BIGQUERY_DATASET_ID;
dataSet = BigQuery.Datasets.insert(dataSet, CONFIG.BIGQUERY_PROJECT_ID);
Logger.log('Created dataset with id %s.', dataSet.id);
}
/**
* Checks if dataset already exists in project.
*
* #return {boolean} Returns true if dataset already exists.
*/
function datasetExists() {
// Get a list of all datasets in project.
var datasets = BigQuery.Datasets.list(CONFIG.BIGQUERY_PROJECT_ID);
var datasetExists = false;
// Iterate through each dataset and check for an id match.
if (datasets.datasets != null) {
for (var i = 0; i < datasets.datasets.length; i++) {
var dataset = datasets.datasets[i];
if (dataset.datasetReference.datasetId == CONFIG.BIGQUERY_DATASET_ID) {
datasetExists = true;
break;
}
}
}
return datasetExists;
}
function createTable(reportConfig) {
if (tableExists(reportConfig.NAME)) {
if (CONFIG.TRUNCATE_EXISTING_TABLES) {
BigQuery.Tables.remove(CONFIG.BIGQUERY_PROJECT_ID,
CONFIG.BIGQUERY_DATASET_ID, reportConfig.NAME);
Logger.log('Truncated dataset %s.', reportConfig.NAME);
} else {
Logger.log('Table %s already exists. Will not recreate.',
reportConfig.NAME);
return;
}
}
// Create new table.
var table = BigQuery.newTable();
var schema = BigQuery.newTableSchema();
var bigQueryFields = [];
// Add account column to table.
var accountFieldSchema = BigQuery.newTableFieldSchema();
accountFieldSchema.description = 'AccountId';
accountFieldSchema.name = 'AccountId';
accountFieldSchema.type = 'STRING';
bigQueryFields.push(accountFieldSchema);
// Add each field to table schema.
var fieldNames = Object.keys(reportConfig.FIELDS);
for (var i = 0; i < fieldNames.length; i++) {
var fieldName = fieldNames[i];
var bigQueryFieldSchema = BigQuery.newTableFieldSchema();
bigQueryFieldSchema.description = fieldName;
bigQueryFieldSchema.name = fieldName;
bigQueryFieldSchema.type = reportConfig.FIELDS[fieldName];
bigQueryFields.push(bigQueryFieldSchema);
}
schema.fields = bigQueryFields;
table.schema = schema;
table.friendlyName = reportConfig.NAME;
table.tableReference = BigQuery.newTableReference();
table.tableReference.datasetId = CONFIG.BIGQUERY_DATASET_ID;
table.tableReference.projectId = CONFIG.BIGQUERY_PROJECT_ID;
table.tableReference.tableId = reportConfig.NAME;
table = BigQuery.Tables.insert(table, CONFIG.BIGQUERY_PROJECT_ID,
CONFIG.BIGQUERY_DATASET_ID);
Logger.log('Created table with id %s.', table.id);
}
function tableExists(tableId) {
// Get a list of all tables in the dataset.
var tables = BigQuery.Tables.list(CONFIG.BIGQUERY_PROJECT_ID,
CONFIG.BIGQUERY_DATASET_ID);
var tableExists = false;
// Iterate through each table and check for an id match.
if (tables.tables != null) {
for (var i = 0; i < tables.tables.length; i++) {
var table = tables.tables[i];
if (table.tableReference.tableId == tableId) {
tableExists = true;
break;
}
}
}
return tableExists;
}
function processReports(folder, accountId) {
var jobIds = [];
// Iterate over each report type.
for (var i = 0; i < CONFIG.REPORTS.length; i++) {
var reportConfig = CONFIG.REPORTS[i];
Logger.log('Running report %s for account %s', reportConfig.NAME,
accountId);
// Get data as csv
var csvData = retrieveAdwordsReport(reportConfig, accountId);
// If configured, back up data.
if (CONFIG.WRITE_DATA_TO_DRIVE) {
var fileName = reportConfig.NAME + '_' + accountId;
folder.createFile(fileName, csvData, MimeType.CSV);
Logger.log('Exported data to Drive folder ' +
CONFIG.DRIVE_FOLDER + ' for report ' + fileName);
}
// Convert to Blob format.
var blobData = Utilities.newBlob(csvData, 'application/octet-stream');
// Load data
var jobId = loadDataToBigquery(reportConfig, blobData);
jobIds.push(jobId);
}
return jobIds;
}
function retrieveAdwordsReport(reportConfig, accountId) {
var fieldNames = Object.keys(reportConfig.FIELDS);
var report = AdWordsApp.report(
'SELECT ' + fieldNames.join(',') +
' FROM ' + reportConfig.NAME + ' ' + reportConfig.CONDITIONS +
' DURING ' + CONFIG.DEFAULT_DATE_RANGE);
var rows = report.rows();
var csvRows = [];
// Header row
csvRows.push('AccountId,'+fieldNames.join(','));
// Iterate over each row.
while (rows.hasNext()) {
var row = rows.next();
var csvRow = [];
csvRow.push(accountId);
for (var i = 0; i < fieldNames.length; i++) {
var fieldName = fieldNames[i];
var fieldValue = row[fieldName].toString();
var fieldType = reportConfig.FIELDS[fieldName];
/* Strip off % and perform any other formatting here.
if ((fieldType == 'FLOAT' || fieldType == 'INTEGER') &&
fieldValue.charAt(fieldValue.length - 1) == '%') {
fieldValue = fieldValue.substring(0, fieldValue.length - 1);
}*/
// Add double quotes to any string values.
if (fieldType == 'STRING') {
fieldValue = fieldValue.replace(',', ''); //Handle fields with comma in value returned
fieldValue = fieldValue.replace('"', ''); //Handle fields with double quotes in value returned
fieldValue = fieldValue.replace('+', ''); //Handle fields with "+" in value returned
fieldValue = '"' + fieldValue + '"';
}
csvRow.push(fieldValue);
}
csvRows.push(csvRow.join(','));
}
Logger.log('Downloaded ' + reportConfig.NAME + ' for account ' + accountId +
' with ' + csvRows.length + ' rows.');
return csvRows.join('\n');
}
function getDriveFolder() {
var folders = DriveApp.getFoldersByName(CONFIG.DRIVE_FOLDER);
// Assume first folder is the correct one.
if (folders.hasNext()) {
Logger.log('Folder name found. Using existing folder.');
return folders.next();
}
return DriveApp.createFolder(CONFIG.DRIVE_FOLDER);
}
function loadDataToBigquery(reportConfig, data) {
function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + s4() + s4() + s4() + s4() + s4() + s4();
}
var makeId = guid();
var job = {
jobReference: {
jobId: makeId
},
configuration: {
load: {
destinationTable: {
projectId: CONFIG.BIGQUERY_PROJECT_ID,
datasetId: CONFIG.BIGQUERY_DATASET_ID,
tableId: reportConfig.NAME
},
skipLeadingRows: 1,
ignoreUnknownValues: true,
allowJaggedRows: true,
allowLargeResults: true
}
}
};
var insertJob = BigQuery.Jobs.insert(job, CONFIG.BIGQUERY_PROJECT_ID, data);
Logger.log('Load job started for %s. Check on the status of it here: ' +
'https://bigquery.cloud.google.com/jobs/%s', reportConfig.NAME,
CONFIG.BIGQUERY_PROJECT_ID);
return job.jobReference.jobId;
}
function waitTillJobsComplete(jobIdMap) {
var complete = false;
var remainingJobs = [];
var accountIds = Object.keys(jobIdMap);
for (var i = 0; i < accountIds.length; i++){
var accountJobIds = jobIdMap[accountIds[i]];
remainingJobs.push.apply(remainingJobs, accountJobIds);
}
while (!complete) {
if (AdWordsApp.getExecutionInfo().getRemainingTime() < 5){
Logger.log('Script is about to timeout, jobs ' + remainingJobs.join(',') +
' are still incomplete.');
}
remainingJobs = getIncompleteJobs(remainingJobs);
if (remainingJobs.length == 0) {
complete = true;
}
if (!complete) {
Logger.log(remainingJobs.length + ' jobs still being processed.');
// Wait 5 seconds before checking status again.
Utilities.sleep(5000);
}
}
Logger.log('All jobs processed.');
}
function getIncompleteJobs(jobIds) {
var remainingJobIds = [];
for (var i = 0; i < jobIds.length; i++) {
var jobId = jobIds[i];
var getJob = BigQuery.Jobs.get(CONFIG.BIGQUERY_PROJECT_ID, jobId);
if (getJob.status.state != 'DONE') {
remainingJobIds.push(jobId);
}
}
return remainingJobIds;
}
It appears the "Empty Response" error is being thrown on:
var insertJob = BigQuery.Jobs.insert(job, CONFIG.BIGQUERY_PROJECT_ID, data);
Have tried quite a few tweaks, but the answer doesn't appear to obvious to me. Thanks for any help!
I can be wrong but - I think that problem was with jobId because of issue with guid() function - missing "+" sign.
function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + s4() + s4() + s4() s4() + s4() + s4();
}
Why not to use jobId from Response like below?
var job = {
configuration: {
load: {
destinationTable: {
projectId: CONFIG.BIGQUERY_PROJECT_ID,
datasetId: CONFIG.BIGQUERY_DATASET_ID,
tableId: reportConfig.NAME
},
skipLeadingRows: 1,
ignoreUnknownValues: true,
allowJaggedRows: true,
allowLargeResults: true
}
}
};
var insertJob = BigQuery.Jobs.insert(job, CONFIG.BIGQUERY_PROJECT_ID, data);
Logger.log('Load job started for %s. Check on the status of it here: ' +
'https://bigquery.cloud.google.com/jobs/%s', reportConfig.NAME,
CONFIG.BIGQUERY_PROJECT_ID);
return insertJob.jobReference.jobId;
Added
In this case I would suggest to log jobId (makeId = guid()) and get job status following below link https://cloud.google.com/bigquery/docs/reference/v2/jobs/get#try-it
Enter ProjectId and JobId and you at least will see what is going on with your job!!
AdWords places a "--" in for null values. If you define your report fields as anything but string (e.g., float, integer, etc.) the insert will fail because it can't convert the dash dash to a float or integer.
Try setting all of your fields to string and see if that solves the problem.
Have you tried setting the WRITE_DATA_TO_DRIVE parameter to true to confirm that the report export is successful? How large is the result? I get the same error when attempting an insert greater than 10MB (~25k rows depending on columns). If the file export to Google Drive looks good, you can add a condition to the while loop in retrieveAdwordsReport to limit the file size. There was also a post on https://groups.google.com/forum/#!forum/adwords-scripts mentioning an issue when including AdNetworkType columns: https://groups.google.com/forum/#!searchin/adwords-scripts/adnetworktype2%7Csort:relevance/adwords-scripts/yK57JHCt3Cw/Cl1SjFaQBQAJ.
Limit result size:
var processedRows = 0;
// Iterate over each row.
while (rows.hasNext() && ++processedRows < 5000) {
var row = rows.next();
var csvRow = [];
csvRow.push(accountId);
if (processedRows % 1000 == 0)
{
Logger.log('Processed %s rows.',processedRows);
}
...

Form Submit calling adapter

I have a form that call a procedure onsubmit, this procedure parse the document and create a json object which is passed to an adapter. It seems when the onSubmit procedure end, the call to the adapter is killed and then the onFailure method of the adapter is called.
My question is how I can wait in my onSubmit procedure that the adapter is finished.
If I add a flag in the onSuccess and wait until the flag is set, I will not capture real failure. If I add a flag in the onFailure, as the onFailure is called because the process is killed, I will not be able to wait the end of the process.
It works if I add an alert after the call to the adapter in the onSubmit procedure and wait that the onSuccess is triggered...
Here some code:
function postCustomer(content) {
var invocationData = {
adapter : 'myAdapter',
procedure : 'postCustomerByContent',
parameters : [ content ]
};
WL.Client.invokeProcedure(invocationData, {
onSuccess : postCustomerSuccess,
onFailure : postCustomerFailure,
timeout: 30000
});
}
function postCustomerSuccess(result) {
var httpStatusCode = result.status;
if (200 == httpStatusCode) {
var invocationResult = result.invocationResult;
var isSuccessful = invocationResult.isSuccessful;
if (true == isSuccessful) {
WL.SimpleDialog.show('Title', "Success", [{text : 'OK'}]);
} else {
WL.SimpleDialog.show('Title', "Error. isSuccessful=" + isSuccessful, [{text : 'OK'}]);
}
} else {
WL.SimpleDialog.show('title', "Error. httpStatusCode=" + httpStatusCode, [{text : 'OK'}]);
}
}
function postCustomerFailure(result) {
WL.SimpleDialog.show('Title', "Failed:"+result, [{text : 'OK'}]);
}
function formSubmit() {
var application = document.forms["application"], initial = application["ibmerName"].value, email, name, organizationName = application['organizationName'].value, primaryContactName = application['primaryContactName'].value, primaryContactEmail = application['primaryContactEmail'].value, organizationAddress = application['organizationAddress'].value, primaryContactPhoneNumber = application['primaryContactPhoneNumber'].value, country = application['country'].value, organizationType = application['organizationType'].value;
if (initial == "xxx") {
email = "xxxxxxxxxxxxxxxxx";
name = "xxx";
} else if (initial == "yyy") {
email = "yyyyyyyy";
name = "yyyyyyyyyy";
} else {
email = "xxxxxxxxxxxxxxxxxx";
name = "xxxxxxxxxxxxxxxxx";
}
var content = '{"email":"' + email + '","name":"' + name
+ '","organizationName":"' + organizationName
+ '","primaryContactName":"' + primaryContactName
+ '","primaryContactEmail":"' + primaryContactEmail
+ '","organizationAddress":"' + organizationAddress
+ '","primaryContactPhoneNumber":"' + primaryContactPhoneNumber
+ '","country":"' + country + '","organizationType":"'
+ organizationType + '"}';
postCustomer(content);
alert(content);
}
Any idea?
Thx
is the page refreshing, if so, you have to do a return false at the end of your formSubmit function.

Can I get the failed request id when PhantomJS get resource error?

I don't quite understand why PhantomJS only returns the url of request for onResourceError callback, while for the other two resource callbacks it returns the request id. That makes "finding which request did actually fail" really impossible if there is more than one request to the same url. Does anyone knows how to get the failed request id?
Actually, that's just old documentation. onResourceError has the id of a failed request.
page.onResourceError = function(resourceError) {
console.log('Unable to load resource (request ID:' + resourceError.id + 'URL:' + resourceError.url + ')');
console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
};
Why do you really need to request id ?
Since onResourceError was added in 1.9, some information may be missing.
A way to resolve your problem is to keep in an array all requested resourcessuach as in netsniff example.
Here is a very basic implementation :
var page = require('webpage').create(),
system = require('system');
if (system.args.length === 1) {
console.log('Usage: netsniff.js <some URL>');
phantom.exit(1);
} else {
page.address = system.args[1];
page.resources = [];
page.onLoadStarted = function () {
page.startTime = new Date();
};
page.onResourceRequested = function (req) {
page.resources[req.id] = {
request: req,
startReply: null,
endReply: null
};
};
page.onResourceReceived = function (res) {
if (res.stage === 'start') {
page.resources[res.id].startReply = res;
}
if (res.stage === 'end') {
page.resources[res.id].endReply = res;
}
};
page.onResourceError = function(resourceError) {
console.log('Unable to load resource (URL:' + resourceError.url + ')');
console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
page.resources.forEach(function (resource) {
var request = resource.request,
endReply = resource.endReply;
if (request && request.url === resourceError.url && !endReply) {
console.log('request id was :' + request.id);
}
})
};
page.open(page.address, function (status) {
var har;
if (status !== 'success') {
console.log('FAIL to load the address');
phantom.exit(1);
} else {
page.endTime = new Date();
page.title = page.evaluate(function () {
return document.title;
});
console.log(page.title);
phantom.exit();
}
});
}
onResourceError, you just need to find first/last/all recorded urls that match the error resource url.