Using ‘SendJavscript’ to inject javascript into Android Phonegap application

31 / Jan / 2013 by Prakash Balodi 2 comments

In one of my Android Phonegap projects, I had to pass information from the native java code of my app to the Phonegap code(written in Javascript). I found out that I can do so with ‘sendJavascript()’ method available in DroidGap class. For example, the following line of code will inject a variable in Javscript with value of 10.

PhonegapActivity.this.sendJavascript(“javascript:var injectedVariable=10;”) //PhonegapActivity – Activity that extends DroidGap class

Moreover, as various activites in an Android app communicate with each other by using intents, the Phonegap activity can be configured to handle data sent by other activities and passing it to the Javascript by over-riding the ‘onNewIntent()’ method in Phonegap Activity. For example –

public void onNewIntent(Intent intent) {
String data=intent.getStringExtra(“data”);
PhonegapActivity.this.sendJavascript("javascript:var data="+data+”;”);


Thus, we can intercept the event to obtain the data, then pass it along to Phonegap and process it according to our requirement in Javascript.

Tag -


comments (2)

  1. Jason Axley

    FYI, your example here may be vulnerable to another application executing XSS in the context of your application. You are taking data input from an Intent that you may not be wise to trust. If your security permissions for your activities are not locked down (or if this code exists in your home activity which is exported by default), a malicious application could launch your activity and pass arbitrary javascript that you would have just executed. Should input-validate the data on the intent and output-encode the data (javascript hex encoding) for maximum safety.

    If your activity is exported, than any app on your device could launch it from any intent and thus the intent is not to be trusted.

    Be careful what sensitive data you send around inside the intent as well since that could possibly be sniffed by other applications.


Leave a comment -