Casperjs fill input without name - phantomjs

i want to use facebook share dialog
Link to share dialog
with casperjs
i managed to select the post mode "group" from the first dropdown , but i failed when i tired to fill the group name input (i think it use ajax drop down list)
Screenshot of result
with no luck , here is my code .
var casper = require('casper').create({
pageSettings: {
loadImages: false,
loadPlugins: true,
userAgent: 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0'
},
logLevel: "info",
verbose: true
});
casper.options.stepTimeout = 60000;
var fs = require('fs');
var x = require('casper').selectXPath;
var x1 = require('casper').selectXPath;
casper.start('http://facebook.com/login.php', function() {
console.log("page loaded");
this.test.assertExists('form#login_form', 'form is found');
this.fill('form#login_form', {
email: 'email',
pass: 'pass'
}, true);
this.wait(1000, function() {
casper.capture('login.png');
console.log("screen captured");
});
});
casper.thenOpen('https://www.facebook.com/dialog/share?app_id=966242223397117&redirect_uri=http://www.facebook.com/dialog/return/close&display=popup&href=http://www.isearchforjob.com/', function() {
console.log("debug loaded");
this.wait(1000, function() {
casper.capture('debug.png');
console.log("screen captured");
});
if (this.exists('span._55pe')) {
this.click('span._55pe');
casper.then(function() {
this.click(x('//span[text()="Share in a group"]'))
});
casper.waitForSelector('input#audience_group', function(){
casper.capture('clicked0.png');
this.fillSelectors('form#platformDialogForm', {
'input#audience_group': 'test'
}, false);
casper.capture('clicked01.png');
});
}
});
casper.run();
i tried also
this.sendKeys('#audience_group','group name');

Related

How to log in to CouchDB without entering username & password

When I try to log in to my remote CouchDB instance from my script, a popup login appears.
I want my script to log into CouchDB without the user having to enter the password (I'm authenticating users with the Google People API and then authenticating my offline app against a single CouchDB instance).
Instead of using the username and password in my code, CouchDB is demanding a new one each time, via the popup.
PouchNotesObj = function (databasename, remoteorigin) {
'use strict';
Object.defineProperty(this, 'pdb', {writable: true});
Object.defineProperty(this, 'remote', {writable: true});
Object.defineProperty(this, 'formobject', {writable: true});
Object.defineProperty(this, 'notetable', {writable: true});
Object.defineProperty(this, 'searchformobject', {writable: true});
Object.defineProperty(this, 'errordialog', {writable: true});
Object.defineProperty(this, 'dbname', {writable: true});
var databasename = 'pouchcontacts';
var remoteorigin = 'https://<remote.path>:6984';
var hostUrl = 'https://<myapp>.appspot.com/';
this.dbname = databasename;
this.pdb = new PouchDB(databasename);
var remoteDB = new PouchDB(remoteorigin + '/pouchnotes', {skip_setup: true});
this.remote = remoteDB;
//from https://github.com/pouchdb-community/pouchdb-authentication/issues/121
var user = {
cname: 'myusername',
password: 'mypassword'
};
var pouchOpts = {
skip_setup: true
};
var ajaxOpts = {
ajax: {
headers: {
'X-Auth-CouchDB-UserName': 'myusername',
'X-Auth-CouchDB-Roles': 'user',
'Content-Type': 'application/json; charset=utf-8',
'Authorization': 'Basic ' + window.btoa(user.cname + ':' + user.password),
'Access-Control-Allow-Origin' : hostUrl,
'Access-Control-Allow-Methods': 'GET, DELETE, PUT, OPTIONS',
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With'
}
}
};
remoteDB.login(user.cname, user.password, ajaxOpts, function (err, response) {
if (err) {
if (err.cname === 'unauthorized' || err.cname === 'forbidden') {
console.log('Unauthorised user');
} else {
//return this.remote.all_docs();
console.log('Successful login');
}
}
});
this.remote.info()
.then(console.log.bind(console))
.catch(console.log.bind(console));
// https://glebbahmutov.com/blog/synching-db/
this.pdb.replicate.to(this.remote, {
live: true,
retry: true
}).on('change', function (change) {
console.log('data change (replicate TO): ', change)
}).on('error', function (err) {
console.log('sync error (replicate TO): ', err)
});
this.pdb.replicate.from(this.remote, {
live: true,
retry: true
}).on('change', function (change) {
console.log('data change (replicate from): ', change)
}).on('error', function (err) {
console.log('sync error (replicate from): ', err)
});
};
Update:
I have now configured my CouchDB instance with all the parameters required for Proxy Authentication.
My script now looks like this:
/* Login to CouchDB on remote */
var pouchOpts = {
skip_setup: true
};
var ajaxOpts = {
ajax: {
headers: {
'X-Auth-CouchDB-UserName': 'my-user-name',
'X-Auth-CouchDB-Roles': 'user',
'X-Auth-CouchDB-Token': hex_hmac_sha1('couch_secret', 'Brookes'),
'Content-Type': 'application/json; charset=utf-8',
'Access-Control-Allow-Methods': 'GET, DELETE, PUT, OPTIONS',
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With'
}
}
};
var remoteSession = 'https://my-couch-server:6984/_session';
remoteSession.login(ajaxOpts, function (err, response) {
if (err) {
if (err.cname === 'unauthorized' || err.cname === 'forbidden') {
console.log('Unauthorised user');
} else {
//return this.remote.all_docs();
console.log('Successful login');
var remoteDB = new PouchDB('https://my-couch-server:6984/pouchnotes', {skip_setup: true});
}
}
});
/*end couch login*/
The error message I am getting is remoteSession.login is not a function
If I go to _session on my CouchDB host, I get the following:
{"ok":true,"userCtx":{"name":"my-admin-user","roles":["_admin"]},"info":{"authentication_db":"_users","authentication_handlers":["cookie","default"],"authenticated":"default"}}
CouchDB provides a token based authentication mechanism that may help in your case.
I point you to another answer where this mechanism is proposed.
The Proxy Authentication is described here.

WebdriverIO - Get browser logs

I want to get the browser logs (console.logs) from chrome with WebdriverIO's log functionality but all I get is, that the function log is not a function.
var WebdriverIO = require('webdriverio');
var chai = require('chai');
var _ = require('lodash');
var chaiAsPromised = require('chai-as-promised');
var expect = chai.expect;
chai.use(chaiAsPromised);
var browser = {
host: '127.0.0.1',
port: 4444,
desiredCapabilities: {
browserName : 'chrome',
chromeOptions: {
args: [
'no-sandbox',
'use-fake-device-for-media-stream',
'use-fake-ui-for-media-stream',
'mute-audio',
]
},
loggingPrefs: {
'driver': 'INFO',
'browser': 'INFO'
}
},
};
var matrix = WebdriverIO.multiremote({
browserA: browser,
browserB: browser,
});
chaiAsPromised.transferPromiseness = matrix.transferPromiseness;
var browserA = matrix.select('browserA');
var browserB = matrix.select('browserB');
it('should initialize browsers', function() {
return matrix.init();
});
it('should open two browsers', function(done) {
browserA.url('https://127.0.0.1:3000/');
browserB.url('https://127.0.0.1:3000/');
matrix.timeouts('implicit', 15000);
matrix.sync().call(done);
});
it('should return logs', function(done) {
browserA
.log('browser', function(err, msg, a) {
console.log(msg);
})
.call(done);
});
Does someone know how to use this function properly? It also doesnt work when I just use one browser and not creating a Matrix like I did in the code snippet.
You are using the API wrong. You can not pass in a callback to the log method. The command returns a promise (if you use a standalone script like that) so you need to do:
browserA
.log('browser').then(function(msg) {
console.log(msg);
})

Phantom.js .NET authentication failure

Once I submit the form (either by form.submit() or element.click()), the page reloads but, is not redirected to the authenticated side of the site. It's simply the same page as the authentication failed page. The difference though is that, the new rendered page has the password removed from the password field.
var page = require('webpage').create();
page.onUrlChanged = function(url) {
console.log('Change to: ' + url);
};
page.onResourceError = function(resourceError) {
page.reason = resourceError.errorString;
page.reason_url = resourceError.url;
};
page.settings.userAgent = 'Mozilla/46.0.1 (X11; Linux x86_64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.71 Safari/537.36'
page.viewportSize = { width: 1280, height: 1024 };
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.open('https://www.some site/default.asp',function(status) {
console.log("Status: " + status);
if(status === "success") {
page.evaluate(function() {
console.log("set values in a aform");
var x=document.getElementsByTagName("input");
x[8].value="blaa";
x[9].value="blaa";
x[10].value="blaa";
x[11].click();
});
window.setTimeout(function () {
phantom.exit();
}, 9000);
page.render('bsplogin1.png');
}
else{
console.log( "page not open!" );
phantom.exit( 0 );
}});

Chrome, recognize open tab

I'm creating an extenstion for google chrome that will perform checking if a stream on twitch.tv is online and will notify the user evey X minutes, I got that covered. What I'm looking for is a JScirpt code that will recognize if user is already on the streamers channel and will stop notifying him.
var username="$user";
setInterval(check,300000);
function check()
{
request("https://api.twitch.tv/kraken/streams/" + username, function() {
var json = JSON.parse(this.response);
if (json.stream == null)
{
chrome.browserAction.setIcon({ path: "offline.png" });
}
else
{
notify();
}
});
return 1;
}
function notify(){
var opt = {type: "basic",title: username + " is streaming!",message: "Click to join!",iconUrl: "start.png"};
chrome.notifications.create("", opt, function(notificationId)
{
setTimeout(function()
{
chrome.notifications.clear(notificationId, function(wasCleared) { console.log(wasCleared); });
}, 3000);
});
chrome.browserAction.setIcon({path:"online.png" });
}
chrome.browserAction.onClicked.addListener(function () {
chrome.tabs.create({ url: "http://www.twitch.tv/"+username });
});
function request(url, func, post)
{
var xhr = new XMLHttpRequest();
xhr.onload = func;
xhr.open(post == undefined ? 'GET' : 'POST', url, true);
xhr.send(post || '');
return 1;
}
check();
Use window.location.href to get the complete URL.
Use window.location.pathname to get URL leaving the host.
You can read more here.

Invalidate session with custom authenticator

Using ember-cli 0.1.2 and ember-cli-simple-auth 0.7.0, I need to invalidate the session both on client and server. As explained here I need to do something similar to the authenticate method making an ajax request to the server and ensuring its success before emptying the session:
import Ember from 'ember';
import Base from "simple-auth/authenticators/base";
var CustomAuthenticator = Base.extend({
tokenEndpoint: 'http://127.0.0.1:3000/api/v1/auth/login',
restore: function(data) {
},
authenticate: function(credentials) {
var _this = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.ajax({
url: _this.tokenEndpoint,
type: 'POST',
data: JSON.stringify({ email: credentials.identification, password: credentials.password }),
contentType: 'application/json'
}).then(function(response) {
Ember.run(function() {
resolve({ token: response.token });
});
}, function(xhr, status, error) {
var response = JSON.parse(xhr.responseText);
Ember.run(function() {
reject(response.error);
});
});
});
},
invalidate: function() {
var _this = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.ajax({
url: _this.tokenEndpoint,
type: 'DELETE'
}).then(function(response) {
resolve();
}, function(xhr, status, error) {
var response = JSON.parse(xhr.responseText);
Ember.run(function() {
reject(response.error);
});
});
});
}
// invalidate: function() {
// var _this = this;
// return new Ember.RSVP.Promise(function(resolve) {
// Ember.$.ajax({ url: _this.tokenEndpoint, type: 'DELETE' }).always(function() {
// resolve();
// });
// });
// }
});
export default {
name : 'authentication',
before : 'simple-auth',
initialize : function(container) {
container.register('authenticator:custom', CustomAuthenticator);
}
};
My logout API endpoint need the token (in the headers). How do I pass it? I read this but my authorizer seems ignoring it and I got a 401:
import Ember from 'ember';
import Base from 'simple-auth/authorizers/base';
var CustomAuthorizer = Base.extend({
authorize: function(jqXHR, requestOptions){
Ember.debug("AUTHORIZING!");
}
});
export default {
name : 'authorization',
before : 'simple-auth',
initialize : function(container) {
container.register('authorizer:custom', CustomAuthorizer);
}
};
My environment.js:
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'wishhhh',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
// TODO: disabled because of https://github.com/stefanpenner/ember-cli/issues/2174
ENV.contentSecurityPolicyHeader = 'Disabled-Content-Security-Policy'
ENV['simple-auth'] = {
authorizer: 'authorizer:custom',
// crossOriginWhitelist: ['http://localhost:3000']
crossOriginWhitelist: ['*']
}
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'auto';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
The following is the Ember inspector output when, eventually, I try to logout:
Did you actually configure Ember Simple Auth to use your custom authorizer? In that case it should authorize the session invalidation request automatically.
Alternatively you could add the token in the authenticator's invalidate method which gets passed the session's contents.
Thanks to marcoow, I found out that it was actually a problem with every request not only the logout one. My authorizer never got called. Problem was environment setup of crossOriginWhitelist which, in order to work with my dev API, I had to set to ['http://127.0.0.1:3000']. Neither ['http://localhost:3000'] nor [*] worked.