Performing user events

In some cases, we will need to emulate user keyboard events and mouse events. PhantomJS provides a simple function to trigger these events from our script. These events will provide necessary actions in our script, from clicking on a URL to inputting usernames and passwords, or just filling up a form.

The function sendEvent, from the WebPage API, has the capability to perform these events on the page from our scripts.

page.sendEvent(eventType[,event specific arguments])

There are two types of events that are supported: keyboard and mouse events. Each event differs by the set of arguments that can be passed to the functions to match the necessary data to perform the event.

Keyboard events

Let us first explore how to use key events. The following is the complete function signature for the key event.

page.sendEvent(keyEventType, keyOrKeys, null, null, modifier).

The key event type can be either 'keypress', 'keydown', or 'keyup'. The second argument can be a single character or a string of characters. We can reference and use the page.event.key object for built-in constants. We can use the page.event.key.A for capital letter A, or page.event.key.F1 for triggering the F1 key. Check the Appendix for a list of key constants.

The third and fourth argument is unused, and we can just leave it null. The last argument is the key event modifier, which can be a combination of key modifiers.

Key modifier

No modifier

0

Shift key

0x02000000

Ctrl key

0x04000000

Alt key

0x08000000

Meta key

0x10000000

Keypad button

0x20000000

So, if we are supposed to be sending Ctrl + Shift + Page Down, we can call that in our script by using the following code:

page.sendEvent('keypress', page.event.key.PageDown, null, null, 0x04000000 | 0x02000000)

If we are to visit a page capable of using keys as a shortcut to navigate around the page, like Gmail, for instance, then this will be very useful. We will create a new script that will send these shortcut-keyboard events; however, we will not use Gmail in our example. We will have our own little page that has the capability to display which key was pressed. First, we build up our test page which we will run our PhantomJS script with. We will use jQuery to bind the key events to our page using the following script:

    $(window).keyup(function(event) {
			addEntry(event);
			event.preventDefault(); 
			return false; 
		});
		
		function addEntry(event) {
			var data = "<tr><td>" + 
			    event.type     + "</td><td>" + 
				event.keyCode  + "</td><td>" + 
				event.ctrlKey  + "</td><td>" + 
				event.altKey   + "</td><td>" + 
				event.shiftKey + "</td><td>" + 
				event.metaKey  + "</td></tr>";
			$('#keyEventsBody > tbody:last').append(data);
		}

}

The preceding code is for our test page, and using jQuery we will set up a handler when a keyup function is generated within the page. Our test is to check if the emulated key events from the PhantomJS script will be recognized by our test page. We can add two more event capturing handlers for key down and for key press. The following is the script in PhantomJS:

var system = require('system'),
var page = require('webpage').create();

page.open('keyevents.htm', function(status) {
  if ( status === "success" ) {
    page.render('beforekey.png'),
    
    // sending arrow left key
    page.sendEvent('keypress', page.event.key.Left, null, null, 0);
    
    // sending Ctrl+A
    page.sendEvent('keypress', page.event.key.A, null, null, 0x04000000);
    page.render('afterkey.png'),
    phantom.exit(0);
  }
});

In the preceding code, first we load the test page, then after loading, we capture a screenshot, which should render just the header of the test page. Then, we emulate the key events using the sendEvent function. And finally, we capture the page screen again. In the second screenshot, we expect that this will generate and display the captured events. The following is a sample screenshot:

Keyboard events

Before sendEvent

Keyboard events

After sendEvent

We can use these methods not only for navigation or hotkeys, but also for filling up forms. Especially, on form fields that have JavaScript triggers when the value or a key event is bounded, instead of manipulating the field value and changing them directly.

Mouse events

Aside from key events, we can also emulate mouse events such as mouseup, mousedown, mousemove, click, and doubleclick.

page.sendEvent(mouseEventType, mouseX, mouseY, button='left')

The second and third argument will have the coordinates to which the event will occur relative to the page. The last argument is the button that is triggered when the event occurs; by default, it is set to 'left'.

var point = page.evaluate(function () {
  var element = document.querySelector('#button1'),
  var rect = element.getBoundingClientRect();
  return { 
    x: rect.left + Math.floor(rect.width / 2), 
    y: rect.top + (rect.height / 2) 
  };
});
page.sendEvent('click', point.x, point.y);

The preceding code is a snippet where a button needs to be clicked. Here, we tried to access the #button1 element by selecting it from our page. In the line following this, we extract the bounding boundaries of the element using the getBoundingClientRect function. This function will return an object based on the element's location in a page, which can be found using its coordinates and size.

Then, we compute the button's middle point and return it as a JSON object. This coordinate will be used for emulating the mouse click. Whatever code or event that is bound for that button will be performed as if the user physically clicked the mouse device.

Webpage events are easily emulated or captured in PhantomJS. Using our script, we can actually perform automated web browsing with anticipated possible event scenarios, which will give us more ways to perform web testing and scraping. Along with this, PhantomJS also allows us to trigger user events such as keyboard and mouse events, which will give us more ways to create simulated scenario test. In the next chapter, we will learn how to capture errors that affect PhantomJS and our script.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.109.102