Capturing Events From a Titanium WebView to App Code

Capturing Events From a Titanium WebView to App Code

March 3, 2011

This tutorial explains the process behind capturing events fired from within a WebView component back in your Titanium 'app.js' or javascript code. I will explain this process via the simple idea of capturing a link 'click' event and passing that back to our app.js file, where we can open show the user a dialog and give them a choice about how to open it, rather than it just redirecting within the same WebView container.

Before you begin, create a new project in Titanium Appcelerator and call it whatever you like; I will refer to it here on in as 'WebUITest'.

Step 1) In your app.js file, create a new webview and add it to your window. You use the window and tab views generate by Titanium Developer if you like. Our webview is going to reference a HTML file called 'test.htm'. 


Step 2) Now create a file called 'test.htm' and put it into your Resources directory. This is the HTML file our webview object is going to reference. Edit the HTML file and paste in the following code (note that you must have a valid HTML/BODY tag for this to work, for whatever reason the events may not fire if you are not using a valid HTML document).


Step 3) Go back to your app.js code now and add in the following code. This will capture the event we fired called 'openLink' and will then open the link in Safari. Note how we are getting the parameter we created within the HTML file code called 'linkUrl' via the use of the sender properties (e object) in our openLink function.


That's it - the basics of how to fireEvents and capture them from WebViews back to your Titanium project. Try to extend the project by adding a PickerView or OptionDialog in your openLink function that gives the user the option to save the link, open in safari or copy it to the clipboard. There's many uses for the fireEvent method!