Thursday, 19 June 2014

Add javascript event handlers to frames and iframes of web page

Hi All,

Those who are familiar with javascript would know, how powerful are javascript event handlers and how it makes their life easier in web applications.

Javascript event handlers are inserted at document or at individual element level in web sites and they listen for the specific events and perform the required actions as defined by the developer.

You can find the definition about events and its various types here: http://www.w3schools.com/js/js_events.asp

Events can be inserted into web pages with help of below mentioned methods:

i) addEventListener (for firefox, chrome and IE 9+ browsers)
ii) attachEvent (for IE 5-8)

But, when we need to attach event handlers to elements present inside frames and iframes of web pages - we need to do some additional work. In this blog, I am going to explain how to achieve it.

Event handlers can be added into iframes as below:

var iframes = document.getElementsByTagName('iframe');
alert(iframes.length);

document.iframes[0].contentDocument.addEventListener('click',callback,false);
function callback(e){
alert(123);
}
For adding into Frames, you can use the below statement:

var frames = document.getElementsByTagName('frame');
alert(frames.length);

parent.frames[0].document.addEventListener('click',callback,false);
function callback(e){
alert(123);
}



Wednesday, 18 June 2014

Eclipse Kepler - Network Connection - Socks Proxy Bypass Issue

In this post, I am going to describe about how to overcome one of the Eclipse Kepler issue that bogged me for few days before identifying it.

Before getting into issue, I would like to cover some basic information related to 'Network Connections' preferences of Eclipse.

Most of the Eclipse users would have set the proxy in the 'Network Connections' preference settings during their course of work. For long time, I had a question of what is its significance and what does the options 'native', 'direct' and 'manual' means.

As far as its significance is concerned, during plugin installation and updates - Eclipse would directly contact the internet and download the updates. If you are sitting behind proxy, then Eclipse would not be able to successfully connect to internet and would be hanging whenever we attempt to make the connection.

To address this, we are required to mention the proxy details in the 'Network Connections' preferences of Eclipse. Eclipse provides us with 3 options here:

a. Direct - Makes the connection directly without the aid of any proxies. If you are connecting to internet only through proxy, then this option would not help you and you need to change it to either native or manual.
b. Native - Makes the connection using the proxy set at the OS level. With this option, eclipse fetches the proxy details that you would have set from your browsers (Tools --> Intenet Option --> Connections --> LAN Settings) and uses it.
c. Manual - Makes the connection with user provided proxy details. As far as 'Manual' option is concerned, we can set the proxy value for the protocols 'http', 'https' and 'socks' in it.

Coming back to the issue that bogged me, whenever we set the proxy values for the above mentioned 3 protocols - looks like, Eclipse Kepler would ignore http and https protocol and tries to establish the internet connection only using 'socks' protocol.

If your update site does not support communication using 'socks' protocol, then Eclipse could not make connection and it would hang indefinitely.

Fortunately, people have found this bug and identified the work around for it. Work around is simple just clear the proxy details under 'socks' and proceed. It worked for me and helped me resolve the issue!!

You can refer this blog for more details: http://oakgreen.blogspot.jp/2011/10/eclipse-proxy-settings-bug-and.html 

Tuesday, 17 June 2014

Firefox addon - Pass data between addon script and content script

In this blog, I am going to describe how to pass data between addon script and content script of Firefox addon.

Those familiar with Firefox addon would know about addon script and content script files.

Firefox sdk provides various apis to interact with local system attributes such as registry keys, clipboard content, context menu etc. And these apis could be accessed from a script called addon script (main.js under lib folder of addon).

But from this addon script, we cannot access any of the document object that contains the html details of web page that we load in browsers. To access document object, we need to use separate script called content script that could be accessed from data folder. These restrictions are introduced to ensure the security of user information.

This article from developer website provides detailed information about the features of addon script and content script.

As far as communication between addon script and content script, they have a feature called 'port', which enables the user to send and receive data between the scripts.

In this blog, I am explaining about how to send and receive the data using PageMod module. We can also send and receive information from other modules such as tabs and panel.

Have the below code in main.js file:

pageMod.PageMod({
  include: "*",
  contentScriptFile: data.url("textscript.js"),
  contentScriptWhen: "ready",
  onAttach: startListening
});

function startListening(worker) {
    worker.port.emit('check','test emit');
}

Here, we are attaching 'startListening' function with PageMod object and it emits a message 'test emit' with the user defined event 'check'.

And in contentscript, below code will capture the data emitted by addon script:

self.port.on('check', function(message) {
 console.log(message);
});

Similarly, you can emit the message from content script and can receive it in addon script. You can find those details here: https://developer.mozilla.org/en-US/Add-ons/SDK/Guides/Content_Scripts

Monday, 16 June 2014

Install Mozilla Firefox addon programmatically

This blog summarizes the procedure to install Mozilla Firefox addon programmatically.

We do have a command '-install-global-extension' to install addons for the firefox versions that are earlier than ver 3.6. (Refer: https://support.mozilla.org/en-US/questions/729981)

For the latest firefox versions, Mozilla does not support the above mentioned command. Hence we need to install addons through some work arounds.

This blog details about how to install addons programmatically for latest versions of firefox, which do not support '-install-global-extension' command.

Usually, firefox addons are installed at the user level and not at the system level. In other words, if you install a firefox addon - it will be available only for the user who installed it. If another user logins to the same machine with his credentials, addon will not be available to him/her.

User can install the addon either by dragging and dropping the .xpi files into firefox browser or by placing the xpi file in the below location:

C:\Users\<User>\AppData\Roaming\Mozilla\Firefox\Profiles\<.default>\extensions

If user installs the addon by placing the .xpi file in the above location, firefox will prompt the user to install the addon at the next launch of firefox.

Some points to be noted here:

1. Usually 'AppData' folder will be a hidden folder. Hence we need to change the windows folder setting to display it.
2. '.default' folder will precede with some random text. For every user, this random text will change. Hence we need to handle this programmatically.
3. We need to ensure that .xpi file is named with the same value of '<em:id>' parameter as defined in the install.rtf file.

So, to install addon programmatically, we just need to copy and paste our .xpi file into the location mentioned above. Below code mentions how to find the .default file using regular expression. After finding the location, you are just required to copy and paste the xpi file into the identified location:


import java.io.File;
import java.io.FileFilter;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.RegexFileFilter;

public class New {
                static String dataFolder = System.getProperty("user.home") + "\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles";
               
  public static void main(String[] args) {
                 File dir = new File(dataFolder);
                 FileFilter fileFilter = new RegexFileFilter(".*default");
                 File[] files = dir.listFiles(fileFilter);
                 File extDir = new File(files[i]+"\\extensions")
}
}

Please let me know if you have any queries with respect to above explanation.

Monday, 6 August 2012

Eclipse plugin to generate dynamic text


Hello Everyone,

In this post, I would like to share my learning about how to create a eclipse plugin that generates the code in code editor dynamically. This was really a frustrating period for me, as I was working on this particular thing for more than 10 days. I did receive vital information from several blogs and websites - but the information were scattered and I had to assemble them. So, in this blog I am planning to explain the sequence of flow from the scratch to end in the process of creating an eclipse plugin that would generate/populate the code in code editor dynamically.

Step 1:

First step in this process is to create an eclipse plugin. I referred the blog post mentioned here to gather information, and this post provides us with the comprehensive information about the process of creating an eclipse plugin.

http://www.nakedtechnologist.com/?p=677
http://www.nakedtechnologist.com/?p=1179

Step 2:

After creating a plugin, we need to reference the external jars that we are planning to use in our program with the plugin project. With plugin project, we need to follow different procedure for referencing the jar files. Post mentioned below summarizes the steps involved in referencing external jars with plugin project:

http://stackoverflow.com/questions/5744520/adding-jars-to-a-eclipse-plugin

Step 3:

Next step is to make use of eclipse's IDocument class in our java program which would update our code editor with texts dynamically. Below code snippet can be used for it:


private IWorkbench wb = null;
private IWorkbenchWindow win = null;
private IWorkbenchPage page = null;
private IEditorPart part = null;
private CompilationUnitEditor compEditor = null;
private IEditorInput input = null;
private IDocumentProvider dp = null;
private IDocument doc = null;
int offset = 0;

wb = PlatformUI.getWorkbench();//.getActiveWorkbenchWindow().getActiveWorkbenchPage();
win = wb.getActiveWorkbenchWindow();
page = win.getActivePage();
part = page.getActiveEditor();
if (!(part instanceof CompilationUnitEditor))
return;
compEditor = (CompilationUnitEditor)part;
input = ((IEditorPart) compEditor).getEditorInput();  

dp = ((ITextEditor) compEditor).getDocumentProvider(); //editor.getDocumentProvider();
doc = dp.getDocument(input);//editor.getEditorInput());

try {
offset = doc.getLineOffset(doc.getNumberOfLines()-4);
    } catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
doc.replace(offset, 0, UpdateStr+"\n");
    } catch (BadLocationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

For further references, you can refer these posts:
http://wiki.eclipse.org/FAQ_How_do_I_insert_text_in_the_active_text_editor%3F

Step 4:
Usage of IDocument would require the reference of following jar files:

org.eclipse.jface.text;bundle-version="3.7.0",
 org.eclipse.ui.workbench.texteditor;bundle-version="3.7.0",
 org.eclipse.jdt.ui;bundle-version="3.7.0"

User has to reference these jar files as per the procedure mentioned in Step 2 of this post.

But even after referencing the jars, user has to ensure that these jar files are mentioned as part of 'Require bundle' package in 'Manifest.MF' file of eclipse plugin.

If these jar files are not mentioned as part of 'Require Bundle', user has to make them by following these steps:

1. Navigate to 'Dependencies' tab of 'Manifest.MF' file.
2. Under 'Required Plugins' section, search for the mentioned files and add them as required plugin.

These are the steps that I followed while developing the plugin. Please let me know if you face any difficulties during your setup.

Thanks!



Tuesday, 26 June 2012

Selenium WebDriver - Browsermob Proxy Integration

Hello Everyone,

In this post, I would like to share my learning related with 'Selenium Webdriver' - 'Browsermob Proxy' integration. Browsermob proxy is one of the proxy that has been closely integrated with Selenium.

When we use browsermob proxy with Selenium, we can intercept the http requests and responses that pass through the established selenium browser session. Now, I would like to explain how to integrate Selenium Webdriver with browsermob proxy using java.

For any queries related to browsermob-proxy, you can refer the below website: http://opensource.webmetrics.com/browsermob-proxy/

Softwares required:

1. Latest Selenium java files from Selenium website (Version that I used here is Selenium 2.23).
2. Download the Browermob proxy zip file from the above mentioned website (Version that I used is Browsermob-proxy v6).
3. Mozilla Firefox version supported by Selenium (I used Firefox 8.0.1).

Steps:

1. Unzip the Browsermob-proxy zip file.
2. Create new project in Eclipse ide, lets say Browsermob.
3. In eclipse, right click on the project and choose 'Properties'.
4. Navigate to 'Java Build Path' and select the 'Libraries' tab.
5. Click on the 'Add External Jar' option.
6. Add all the jar dependencies of Selenium jar.
7. Then add the jar dependencies of Browsermob-proxy under 'lib' folder of the unzipped Browsermob-proxy zip file.
8. Now, create a new class and copy and paste the below code:


public class Test_One {

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
ProxyServer server = new ProxyServer(8105);
         server.start();
         server.setCaptureHeaders(true);
       
         server.setCaptureContent(true);
         server.newHar("test");
         DesiredCapabilities capabilities = new DesiredCapabilities();
         Proxy proxy = server.seleniumProxy();
         FirefoxProfile profile = new FirefoxProfile();
         profile.setAcceptUntrustedCertificates(true);
         profile.setAssumeUntrustedCertificateIssuer(true);
         profile.setPreference("network.proxy.http", "localhost");
         profile.setPreference("network.proxy.http_port", 8105);
         profile.setPreference("network.proxy.ssl", "localhost");
         profile.setPreference("network.proxy.ssl_port", 8105);
         profile.setPreference("network.proxy.type", 1);
         profile.setPreference("network.proxy.no_proxies_on", "");
         profile.setProxyPreferences(proxy);
         capabilities.setCapability(FirefoxDriver.PROFILE,profile);
         capabilities.setCapability(CapabilityType.PROXY, proxy);
         WebDriver driver = new FirefoxDriver(capabilities);
         driver.get("http://www.google.com");
         Har har1 = server.getHar();
         }
}

}


Execute the above code. You can observe that proxy would have been created in the port 8105 and all the Http Requests and Responses would be passed via the proxy.

You can further refer about HAR files in order to obtain the required information about how to access http requests & responses from the HAR files.

Please let me know if you have any queries on this.





Thursday, 19 April 2012

Selenium Android User Actions


In this article, I would describe about how to emulate the various user actions such as doubletap, singletap, flick etc using Selenium in Android Mobile Browser.

Before getting into the technical details, as most of us know, Selenium is the leading test automation tool for web application and it works using the inbuild javascript support of the browsers. As almost all the browsers support javascripts, selenium can be used to automate web applications in virtually any browsers. Same applies to the browsers in mobile devices as well.

Android devices as an inbuild browser called ‘Android Browser’, and Selenium has a separate module that can be used to automate ‘Android Browser’.

Details about how to use ‘Selenium Android Package’ for mobile automation can be found in this link: http://code.google.com/p/selenium/wiki/AndroidDriver

Above web page has the detailed description about how to automate Android using Selenium (ofcourse we need patience during the initial setup, as we would commit some inadvertent mistakes while setting up).  So, I would give you a code snippet that performs user actions such as doubletap, singletap,flick using Selenium in this article.


AndroidDriver driver = new AndroidDriver();
driver.get(www.testapp.com”);
WebElement elem = driver.findelement(By.id(“name”));
      Action TchAct = new TouchActions(driver).doubleTap(elem).build();
      TchAct.perform();
TchAct = new TouchActions(driver).singleTap(elem).build();
      TchAct.perform();
                TchAct = new TouchActions(driver) .flick(element,0,-400,FlickAction.SPEED_NORMAL).build();
      TchAct.perform();

Here we are using ‘Action’ and ‘TouchActions’ classes of Selenium to emulate the user actions. And these actions emulates the user behavior as expected. As mentioned above, Selenium supports other user actions such as longpress, scroll, up, down etc.

Please let me know if you have any clarifications on this article.