Because you’re going to need them…graphic_build_bot

So working with the InAppBrowser is a good way of getting external web content inside your app without too many issues, simply write the following code:

1
2
3
4
ref = window.open('http://www.google.com', '_self', 'location=no');
ref.addEventListener('loadstop', function() {
	//Page loaded! some code here..
});

Right? Wrong! Sadly it’s not always this easy.

First of all, let’s make a few things clear about the parameters used in window.open:

url - yeah I’m not going to explain this one, if you can’t figure it out, you’re out of luck.

target - So this gives you a few options:

  • _self - Cordova WebView if the URL is in the white list, otherwise in the InAppBrowser.

  • _blank - Opens in the InAppBrowser.

  • _system - Opens in the system’s default web browser

The difference between Cordova WebView and InAppBrowser is still unclear to me, and the docs are lacking on that topic.

options - some extra options, the most useful one is hiding the location bar via “location=no”.

There are some pretty useful options like clearcache for android or transitionstyle for iOS.

Now it’s time to talk about injecting JS into the InAppBrowser window, via executeScript.

Obviously going inside the function called on the event “loadstop”, executeScript should allow you to either insert the script string on call:

1
ref.executeSript({code: "alert(‘BLA BLA BLA’)"});
Now pay attention here if you want to attach a file, because if the InAppBrowser opens an external page, it won’t let you inject a local JS file (but string of code? sure! Odd I know). So the creative solution would be to make an Ajax request and inject the code inside the file:
1
2
3
4
5
6
7
8
9
10
11
12
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","main.js",true);
xmlhttp.onreadystatechange = function() {
	//checking that the request was successful
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    	onsuccess(xmlhttp.responseText);
    }
};
onsuccess = function(response) {
	ref.executeScript({code: response });
}
xmlhttp.send();

This solution works pretty well (and no need for jQuery!)

Blank Screen on Back Button

If InAppBrowser is supposed to be the main application window, when pressing the Back Button, you’ll get a blank screen (which is because the InAppBrowser is technically a different window) - which is your default index.html file (unless you changed it).

To avoid that, you’re in luck - InAppBrowser has an exit event! so just throw this in there:

1
2
3
ref.addEventListener('exit', function() {
	navigator.app.exitApp();
});

What works on Android, doesn’t necessarily work on iOS

I know it’s disappointing because PhoneGap is supposed to fix this, but it’s impossible to demand the exact same thing happening across all system.

I’d say PhoneGap gives you about 75%+ same behavior between platforms, but there are numerous options that are platform specific, sometimes - it’s a good thing.