Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //example
- listenAjaxResponses(page, 'getUserDetails', function(responseData)
- {
- // this will be executed within the sandboxed page, not within the phantomjs
- alert('User details has requested!');
- var username = eval('(' + responseData + ')').user.username;
- alert(username);
- });
- //listener for all ajax responses of the page
- function listenAjaxResponses(page, urlPattern, callback)
- {
- page.evaluate(function(urlPattern, callback)
- {
- try
- {
- (function(open)
- {
- XMLHttpRequest.prototype.open = function(method, url, async, user, pass)
- {
- this.addEventListener("readystatechange", function()
- {
- if (url.indexOf(urlPattern) === 0)
- {
- if (this.readyState == XMLHttpRequest.DONE)
- {
- callback(this.responseText);
- }
- }
- }, false);
- open.call(this, method, url, async, user, pass);
- };
- })(XMLHttpRequest.prototype.open);
- }
- catch (ex)
- {
- alert(ex);
- }
- }, urlPattern, callback);
- }
- //create a blank page
- function createPage(viewportSize)
- {
- var page = webpage.create();
- page.settings.webSecurityEnabled = false;
- page.settings.localToRemoteUrlAccessEnabled = true;
- page.settings.userAgent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36';
- if (viewportSize) page.viewportSize = viewportSize;
- page.onAlert = function(error)
- {
- console.log('Alert: {0}'.format(error));
- };
- page.onError = function(error, trace)
- {
- var msgStack = ['ERROR: {0}'.format(error)];
- if (trace && trace.length)
- {
- msgStack.push('TRACE:');
- trace.forEach(function(t)
- {
- msgStack.push(' -> {file}: {line} (in function "{function}")'.format(t));
- });
- }
- console.log('Error: {0}'.format(JSON.stringify(trace)));
- };
- return page;
- }
- //formatting function
- //example 1: 'loren {0} dolor {1} amet'.format(['ipsum', 'sit']) = 'loren ipsum dolor sit amet'
- //example 2: '{city} is a {{0}} of {country}'.format({city: 'London', country: 'Great Britain'}) = 'London is a {0} of Great Britain'
- String.prototype.format = function format()
- {
- if (arguments.length == 0) return this;
- var data;
- if (arguments.length > 1) data = arguments;
- else if (typeof arguments[0] == 'object') data = arguments[0];
- else data = arguments;
- return this.split('{{').map(function(q)
- {
- return q.replace(/\{([^\{\}]+)\}/g, function ($0, $1)
- {
- return data[$1];
- });
- }).join('{').replace(/\}\}/g, '}');
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement