PhoneGap Tutorial Series – #4 Third-Party Plugins (ChildBrowser)
Extending the PhoneGap API – Third-Party Plugins (ChildBrowser)
So the last post was all about editing PhoneGap classes to add a little something extra, today it’s about using a third-party plugin that you may have downloaded from somewhere or gotten from someone.
The plugins that we will be using today are from Jesse MacFayden (aka @purplecabbage on twitter). The original source code for the plugins can be downloaded from github here: https://github.com/purplecabbage/phonegap-plugins.git
If you are using PhoneGap 0.9.6
You can get the entire source for my sample project “HelloPhoneGap” from github here: https://github.com/hutley/HelloPhoneGap
If you are using PhoneGap 1.0
You can get the entire source for my sample project “HelloPhoneGap1.0” from github here: https://github.com/hutley/HelloPhoneGap1.0
What is a PhoneGap Plugin?
Simply enough, a PhoneGap plugin is an extension to PhoneGap that allows access to some piece of native functionality on the phone that PhoneGap doesn’t already provide.
A PhoneGap plugin consists of at least two pieces:
- JavaScript file that defines the functions for accessing the native hooks
- Implementation files written in the native language to interact with native phone features
So for iOS a PhoneGap plugin is a package that consists of at least one JavaScript file and at least a pair of .m and .h Objective-C files that extend the PhoneGapCommand class.
It is possible (depending on the complexity of the plugin) that there will be other files as well such as UIViewControllers, UI.xib files, images, etc.
Installing a Third-Party Plugin
Once you have a copy of the plugin that you want to use, you need to make it accessible to your project. This can be done in a variety ways and the plugin could be located in a number of places. To keep it simple and not venture into a long rant on packaging, we will place our newly acquired plugin in the ${PROJECT_DIR}/Plugins directory.
- General Steps to Follow:
- Download your plugin to your machine somewhere – take note of the location
- Open your XCode project (which was created from the PhoneGap template)
- Locate the Plugins directory within your project (not the PhonGapLib project)
- Right-click and add the files from your downloaded plugin directory. Be sure to check the “copy” and “create group references” checkboxes
- Build the project — you may need to add dependent libraries depending on the plugin
In my HelloPhoneGap example I have copied in two plugins from @purplecabbage:
- ChildBrowser – plugin to open resources in a child browser of the application rather than launching Safari.
- NativeControls – plugin to use native controls like a TabBar and ActionSheet (which I will demonstrate in an upcoming post).
As you can see from the above screenshot, the ChildBrowser plugin has images, a viewController, a .xib file, as well as JavaScript and the PhoneGapCommand implementation. The NativeControls plugin is a bit simpler with just the three typical files.
In order to use these plugins from JavaScript the script files need to be located in the ‘www’ directory and you need to include the proper script file on your HTML page. For peace of mind, I added a build step to copy the .js files from the ${PROJECT_DIR}/plugins directory to the ${PROJECT_DIR}/www.
I execute the following script during the build to copy the files:
#!/bin/sh
# PluginCopy.sh
# HelloPhoneGap
# Created by Hiedi Utley on 3/30/11.
# Copyright 2011 Chariot Solutions, LLC. All rights reserved.
cp -rf ${PROJECT_DIR}/Plugins/*/*.js ${PROJECT_DIR}/www
Note: You will need to chmod the PluginCopy.sh script file once you download it from github in order to build the HelloPhoneGap project.
How To Use the Plugin
Using a plugin is relatively simple, after you have put all the files in place in the project, you just need to include the script file for the plugin on your page. Depending on the plugin – you may need to explicitly “install” the plugin – which just means instantiate an instance of the plugin object and make it available for use.
Typically plugins are added to the window.plugins object and are accessible like window.plugins.somePlugin but sometimes that can get unwieldy and you may want to shorten the reference to something like var somePlugin = window.plugins.somePlugin; for use on your page. It’s up to you…
As for figuring out if you need to explicitly install a plugin, all you need to do is inspect the JavaScript (and/or the README) for the plugin and look for a call to the PhoneGap.addConstructor if that’s there, then you should be able to access the plugin as soon as onDeviceReady() is called. If not – you may need to do a SomePlugin.install() within onDeviceReady before using the plugin.
Sample Code
The following excerpt is from the childBrowser.html page in the HelloPhoneGap project – and there are several things to note:
- line 9 - PhoneGap.js is included before any other plugin files
- line 10 – ChildBrowser.js file is included – this file should be located in the ${PROJECT_DIR}/ www directory
- lines 13-22 – onDeviceReady() method signifies that PhoneGap has been initialized
- line 21 – ChildBrowser.install() exlicitly installs the ChildBrowser plugin. Note some plugins will do this automatically. Check…
- lines 23-34 - openChildBrowser(url) calls the childBrowser.showWebPage(url) function to launch a new UIWebView with the requested URL
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<!-- Change this if you want to allow scaling -->
<meta name="viewport" content="width=default-width; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="HelloPhoneGap.css" type="text/css"/>
<title>HelloPhoneGap</title>
<script type="text/javascript" charset="utf-8" src="phonegap.0.9.4.min.js"></script>
<script type="text/javascript" charset="utf-8" src="ChildBrowser.js"></script>
<script type="text/javascript" charset="utf-8">
var childBrowser;
function onBodyLoad()
{
document.addEventListener("deviceready",onDeviceReady,false);
}
/* PhoneGap has been initialized and is ready to roll */
function onDeviceReady()
{
phoneGapReady.innerHTML = "PhoneGap is Ready";
childBrowser = ChildBrowser.install();
}
function openChildBrowser(url)
{
try {
//both of these should work...
//window.plugins.childBrowser.showWebPage(url);
childBrowser.showWebPage(url);
}
catch (err)
{
alert(err);
}
}
</script>
</head>
<body onload="onBodyLoad()">
<button onclick="openChildBrowser('http://www.google.com');">Open Google</button>
</body>
</html>
So the screenshots show the childBrowser.html page and by clicking on the button, the plugin is called which ultimately instantiates a instance of the ChildBrowserViewController which loads the ChildBrowserViewController.xib file to display a new UIWebView and load the requested URL.
As a side note, I also wanted to be able to open local file resources in my ChildBrowser (which it wasn’t able to do before) so I did edit the plugin files to make this happen. If you are interested in the changes – please peruse the ChildBrowserCommand.m file lines 36-44.
So that’s all for now — next post will concentrate on using the NativeControls (ActionSheet) plugin to interact with the built-in PhoneGap Camera API.



thanks for these tutorials ..they are well written and very helpful…
I have followed this tutorial to the letter and checked I have an instance of the ChildBrowser but as soon as I try showWebPage(‘http://www.google.com’); it just boots me right out the app.
Any ideas?
The app just crashes? There must be something in the console indicating why it crashed. Can you post the log messages?
Nice website and great explanation. However, when I call openChildBrowser(), the following exception is thrown in the debug console:
2011-04-06 19:30:24.350 MyApp [930:707] *** WebKit discarded an uncaught exception in the webView:decidePolicyForNavigationAction:request:frame:decisionListener: delegate: -[__NSCFDictionary setObject:forKey:]: attempt to insert nil value (key: ChildBrowserCommand)
Do you what’s causing this? I’m using Phonegap 0.9.4 with XCode 4. Thanks, Nick
Are you passing a url? openChildBroswer(“http://someurl”);
Yep, I’ve followed your tutorial & my code is along the lines of:
$(“#reference_template li”).click(function(){
// test3
window.plugins.childBrowser.showWebPage(‘http://www.google.com’);
});
// Initialised as in your example:
var childBrowser;
function onBodyLoad()
{ document.addEventListener(“deviceready”,onDeviceReady,false);
childBrowser = ChildBrowser.install();
}
I think the problem *may* be that you are initializing the childbrowser before PhoneGap is ready – try adding childBrowser = ChildBrowser.install(); inside the onDeviceReady() function and not in onBodyLoad.
I got the similar error but the weird thing is it never runs into the onDeviceReady function. Hence the childBrowser cannot be initialized. Any clue?
It works. The reason is i’m using different version of phonegap.
or:
childBrowser.showWebPage(“http://www.google.com”);
Thanks for your help – got it working in the end. I did what you suggested plus put the childBrowser files directly into the plugins directory, rather than in the childBrowser directory (in plugins of course!). Nick
Hi,
I tried to run your example but on line 28 I always get an error “childBrowser” undefined.
I tried to figure out whats the problem with firebug. Line 15 gets called, the listener seems to be added.
Line 20 and 21 are bever called, I guess this is the problem.
Any suggestions what might be the problem?
Cheers,
Christoph
You mentioned firebug. Are you trying to run this on a desktop? It will only work on the iPhone simulator or on a device.
I had the same problem and spent hours figuring out how to solve that…
it seems the new Xcode 4 Phonegap Template at http://www.phonegap.com/2011/03/16/creating-a-phonegap-project-from-the-command-line-for-xcode-4/ provides the Phonegap library in the form of a Framework..
So what you need to do is get inside
ChildBrowserCommand.h, change import “PhoneGapCommand.h” to import
Likewise for ChildBrowserCommand.m on PhoneGapViewController
Hope it works for you
HI tmlee, Would you please elaborate on that one? I’ve done everything and the error persists
You said I have to edit: ChildBrowserCommand.h and change the line:
import “PhoneGapCommand.h” for what line? That’s where Im missing! I know I hace to update ChildBrowserCommand.m as well but idk what else to do.
Thanks in advanced.
-F
I have been trying to load the ChildBrowser plugin for quite a while, but i think i am not importing the plugin in the right way.
I check the copy and create group reference button, but then when i build i get a number of errors of which PhoneGapCommand.h no such file or directory.
Can you help please ?
It sounds like the PhoneGapLib has not been set up — try checking Xcode – Preferences – SourceTrees and see the that PHONEGAPLIB variable is pointing to the correct directory to where you installed phonegap.
Thanks for the answer. That actually solved the issue. Great tutoral.
I’m having the same issue that Olivier mentioned, except the method Hiediutley mentioned did not work for me. I have PhoneGap installed (able to select it from XCode) and I have the PhoneGap.framework, but I always get ‘PhoneGapCommand.h: No such file or directory’.
I’ve included the sourceTree to point to where my phonegap was installed, and the variable is named PHONEGAPLIB. However, I still receive the error stating PhoneGapCommand.h doesn’t exist.
Any ideas? I’m completely stumped. Never really integrated any plugins into PhoneGap
Try update:
#import “PhoneGapCommand.h”
to:
#ifdef PHONEGAP_FRAMEWORK
#import
#else
#import “PhoneGapCommand.h”
#endif
I was able to get it working. My issue was I was using an older version of ChildBrowser and it wasn’t looking for the correct header files in my project. Once I updated to the latest version of ChildBrowser and included those files, everything was fine.
Thanks
helloo, This is very use full to me …..Thanks
in iOS5 can’t close browser …… please help …
Great Post There!!! The Child Browser will be very useful in the app I’m developing. On the other hand, I was wondering if you can post a tutorial on how to use the SplashScreen Plugin. I have been trying to figure it out for a couple of weeks in hopes that it solves a small flickering I’m having at the start of the app between the default orientation splash image and the default splash Image. I have set the corresponding default images for the corresponding orientations in the splash folder of my iPad app but it seems like it loads first the Default-Portrait~ipad.png first and then the Default.png. Again I’m hoping that the plugin solves that problem but I can’t seem to make it work. I believe if I can solve that problem, I can place inside the SplashScreen plugin an animated gif or a div that overlays the content while all the CSS is constructed and then i can fade out the overlay screen and show my content without the flickering. Any help would be greatly appreciated. I have found that a lot of people is having the same problem. Thanks in advance!!!!
I’ll add it to my list. Thanks.
Did anyone ever figure out the error: “TypeError: Result of Expression ‘childBrowser[undefined] is not an object”??
Starting to pull my hair out on this one. Thanks.
Did you remember to “install” the plugin? The Childbrowser does not self install so you have to do it yourself. See my post for more details.
I have to agree with Jason, I’m pulling my hair as well. Followed every single step, went through every single troubleshooting page I could find but I still get the “TypeError: Result of expression ‘childBrowser [undefined]‘ is not an object.” Error.
How do you do “SomePlugin.install() within onDeviceReady”
I think that’s the only part I probably missed.
Please advise.
Thank you for your time!
In the code example —
function onDeviceReady()
19 {
20 phoneGapReady.innerHTML = “PhoneGap is Ready”;
21 childBrowser = ChildBrowser.install();
22 }
I using XCode 4 and PhoneGap 1.0.0
I put this sample code and modify for PhoneGap 1.0.0.
However, It still didn’t work for me as well.
When I click the “botton” and try to open google child browser, I got the following debug message
“2011-08-17 01:02:06.473 external[96141:207] ERROR: Plugin ‘ChildBrowserCommand’ not found, or is not a PGPlugin. Check your plugin mapping in PhoneGap.plist.”
I sure I follow every single step for install this plug-in.
Could you help me to make it work?
The HelloPhoneGap project has not yet been updated to work with PhoneGap 1.0. I would suggest downgrading PhoneGap to 0.9.6 until I get the project updated (which I am actively working on).
Hello, thanks for this great post. I don’t know how often I’ve read it, just to miss nothing. But no idea why I get an “TypeError: Result of expression ‘window.plugins.childBrowser [undefined]‘ is not an object.” Error. Has anyone an idea? I do use XCode 4.1 and phonegap 1.0.0. Thanks in advance
It seems that a few people have run into this so a few things to investigate — 1) is it the childBrowser that is undefined or is it window.plugins? 2) Are the appropriate js files included in your html page? 3) Did you remember to call ChildBrowser.install() in your onDeviceReady event? 4) is the onDeviceReady event firing?
Thank you very, very much for your hints and your fast reply. I’ve double checked everything. At the end of the day the solution is very simple.
phonegap.js and childbrowser.js have to be placed in the root (www) directory.
I’ve stored the files in the www Folder, and changed the path within the header. Now it works perfectly. Thanks again.
Have you declared the plugin in the project plst file ? This need to be done for every plugin since Phonegap 0.9.6. See the FAQ part of phonegap.com for more details
PS: when declaring the plugin enter the name in liwer case in the first columm
Hope that helps
Thank you too. see above.
As for the files needing to be in the root www/ directory that is true BUT there is a PluginCopy.sh file that should be running during the build to copy those files. Make sure that build step is working and you shouldn’t have had to copy them yourself.
One other thing — the project currently doesn’t work with IOS 5 and PhoneGap 1.0 so you may be having issues b/c of that. I am working on updating the project.
Hi. Same problem here. The console says:
Plugin ‘ChildBrowserCommand’ not found, or is not a PGPlugin. Check your plugin mapping in PhoneGap.plist.
How exactly do I need to add the plugin in the PhoneGap.plist? Could someone give me the exact values to put in both columns?
hiediutley, when you say:
“The HelloPhoneGap project has not yet been updated to work with PhoneGap 1.0. I would suggest downgrading PhoneGap to 0.9.6 until I get the project updated (which I am actively working on).”,
are you suggesting that we do not use PhoneGap 1.0 or your script? I am confused…
Thank you.
Roberto
The problem is that between PhoneGap 0.9.6 and 1.0.0 they changed the way that plugins are defined. I have created a new project called HelloPhoneGap1.0 which uses this new pattern. See my latest post from yesterday to get the code. It also consequently has some fixes for the iOS5 as well.
Hi
I use the childbrowser and it works great, at first, but after a wile it stops working.
I made a build and run this afternoon and the childbrowser worked
fine, in several different dynamically loaded ajax pages in my app – over wifi.
Then I had to go out on town and I thought I would test it with 3G, and the childbrowser didnt work at all!?
When I build and run it works great at first, but after a wile it stops, both on wifi and 3G!
I use iOS, xcode 3.2.5, phonegap 0.9.4, jqtouch rev 161.
It seams like if I take a build and run to the device and leave it plugged in, it allways works, but when I disconnect it, it stops working after a wile.
I get this message when it fails:
void SendDelegateMessage(NSInvocation*): delegate (webView:decidePolicyForNavigationAction:request:frame:decisionListener:) failed to return after waiting 10 seconds. main run loop mode: kCFRunLoopDefaultMode
Im getting desperate, can anybody please help me, give me a suggestion, anything?
Did you check to see if your page is prompting the user for something or showing an alert? Is your server up? You could always hook up to a network sniffer and look at the traffic being sent back and forth that might give you some clues.
For anyone coming up with “ERROR: Plugin ‘ChildBrowserCommand’ not found” problem, running Phonegap 1.0.0 on xCode4, a small help I found is setting the plugin keys into the Phonegap.plist section
see more
http://groups.google.com/group/phonegap/browse_thread/thread/5bde04dc4df0f4e3
hi!
I’m using latest phone gap and child browser plugin.
i have changed the child browser that it can load files offline.
and the child browser works fine loading pdfs .docs and so on.
but when i try to open a webpage html or url then it opens the safari browser instead or opens it without the child browser xib.
has anybody else this problem and has a solution?
thanks!!!!!
Haven’t seen that problem – are you sure you are loading your page in the ChildBrowser webview and not the App Delegate webview? If you are loading in the parent webView then you would have to add an entry to the PhoneGap.plist file for the external host you are trying to access otherwise PhoneGap will open Safari.
thank you for your answer!
ok, i tried it again, and i open it now with a javascript as other links to pdfs, like this here
function opendoc(link)
{
PhoneGap.exec(“ChildBrowserCommand.showWebPage”, link );
}
but when i use this with an external website (like this here: http://www.n-tv.de) it crashes with:
“terminate called throwing an exception[Switching to process 3800 thread 0xf503]
sharedlibrary apply-load-rules all
Current language: auto; currently objective-c
(gdb)”
That site works fine in my childBrowser. There are probably more messages above that in your console.
yes there is some more (after crash in the console):
2011-08-31 17:00:03.744 CassinoApp[14912:f503] The view controller returned NO from -shouldAutorotateToInterfaceOrientation: for all interface orientations. It should support at least one orientation.
2011-08-31 17:00:03.780 CassinoApp[14912:f503] View did load
2011-08-31 17:00:03.783 CassinoApp[14912:f503] Opening Url : (null)
2011-08-31 17:00:03.785 CassinoApp[14912:f503] *** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘*** -[NSURL initFileURLWithPath:]: nil string parameter’
*** Call stack at first throw:
(
0 CoreFoundation 0x017f95a9 __exceptionPreprocess + 185
1 libobjc.A.dylib 0x0194d313 objc_exception_throw + 44
2 CoreFoundation 0x017b1ef8 +[NSException raise:format:arguments:] + 136
3 CoreFoundation 0x017b1e6a +[NSException raise:format:] + 58
4 Foundation 0x00096ab6 -[NSURL(NSURL) initFileURLWithPath:] + 90
5 Foundation 0x00096a44 +[NSURL(NSURL) fileURLWithPath:] + 72
6 CassinoApp 0x000041c9 -[ChildBrowserViewController loadURL:] + 137
7 CassinoApp 0x0000321c -[ChildBrowserCommand showWebPage:withDict:] + 796
8 CassinoApp 0x00017a2d -[PhoneGapDelegate execute:] + 527
9 CassinoApp 0x00002de0 -[AppDelegate execute:] + 80
10 CassinoApp 0x00017c9b -[PhoneGapDelegate webView:shouldStartLoadWithRequest:navigationType:] + 536
11 UIKit 0x00491a92 -[UIWebView webView:decidePolicyForNavigationAction:request:frame:decisionListener:] + 291
12 CoreFoundation 0x01769c7d __invoking___ + 29
13 CoreFoundation 0x01769b51 -[NSInvocation invoke] + 145
14 CoreFoundation 0×01797858 -[NSInvocation invokeWithTarget:] + 72
15 WebKit 0x025abc76 -[_WebSafeForwarder forwardInvocation:] + 182
16 CoreFoundation 0x0176aa04 ___forwarding___ + 1124
17 CoreFoundation 0x0176a522 _CF_forwarding_prep_0 + 50
18 CoreFoundation 0x01769c7d __invoking___ + 29
19 CoreFoundation 0x01769b51 -[NSInvocation invoke] + 145
20 WebCore 0x0309f140 _ZL20HandleDelegateSourcePv + 64
21 CoreFoundation 0x017da8ff __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15
22 CoreFoundation 0x0173888b __CFRunLoopDoSources0 + 571
23 CoreFoundation 0x01737d86 __CFRunLoopRun + 470
24 CoreFoundation 0×01737840 CFRunLoopRunSpecific + 208
25 CoreFoundation 0×01737761 CFRunLoopRunInMode + 97
26 GraphicsServices 0x020e71c4 GSEventRunModal + 217
27 GraphicsServices 0x020e7289 GSEventRun + 115
28 UIKit 0x00308c93 UIApplicationMain + 1160
29 CassinoApp 0x0000285f main + 127
30 CassinoApp 0x000027d5 start + 53
31 ??? 0×00000001 0×0 + 1
)
terminate called throwing an exception[Switching to process 14912 thread 0xf503]
sharedlibrary apply-load-rules all
Current language: auto; currently objective-c
(gdb)
well i found a quick workaround for me at the moment: i open an .html file (thats working fine) with the childBrowser where the final page is embedded into an iframe. for the moments that okay but i hope the is a smarter solution for that… thanks for help if you can see anything inside of the console output!
Thanks for your input, I got the childbrowser working on the iPhone.
I have converted my app to Android and I have managed to get the childbrowser to work with ordinary links (.html and .asp pages) but when I try to open a .mp4 video it opens and starts to load but then shuts down the childbrowser directly.
Do you have any input on why this is happening?
Thanks!
Hi
I got the childbrowser working in both iPhone and Android, good.
I have a question about the fbconnect childbrowser.
As a Facebook nob, I just wonder what the difference is if I open the mobilepage for login on Facebook eg http://touch.facebook.com/profile.php?id=12345someidnr… that I found on there webpage in the childbrowser and if I use the fb connect childbrowser and log in with that?
Also, as I have the childbrowser working, what do I have to do to get the fbconnect to work, exept for including the fbconnect files of course?
Thanks again for a great tutorial!
I am trying to get the child browser to open with a specific set of dimensions. Right now it fully opens (1024×768) and covers the whole iPad environment. I found some variables in the ChildBrowserViewController.xib which can modify the dimensions of things like the inner frame, toolbar size, label size and activity indicator. However the whole frame still pops up with a grey background covering all of the screen, even if there is only a small frame in the top left corner.
I found this at the end of the file, but modifying the dimensions has no effect. I would like to have just a small browser window pop up in a corner for things like facebook connect and such.
com.apple.InterfaceBuilder.CocoaTouchPlugin.iPhoneOS
com.apple.InterfaceBuilder.CocoaTouchPlugin.iPhoneOS
Thanks
Adam
See the UIViewController reference for more info BUT add this line into the ChildBrowserCommand after creating the ChildBrowserViewControler
[cont setModalPresentationStyle:UIModalPresentationFormSheet];
You will then need to set the size of the view either in the xib and playing with autoresizing masks or by [[childBrowser view] setFrame:CGRectMake(0, 0, 200, 200)];
I was able to resize the frame and the toolbar using the xib file, both in the interface builder and manually by altering the source code version of the file. However no matter what frame sizes I set the background UIView gets resized to full screen. I was checking around to see if a parent class had autoresizessubviews on or if it was inheriting something that was turning autoresize on. I am not that greate at Obj-C so was not able to find anything. I am thinking that either UIView or NSView are setting it to autoresize.
thank you for your very usefull article,
i’m not very expert in objective-c, but there’s a way for add an additional parameter to the showwebpage for force landscape or set the orientation of the dice on the new window?
also something like file.html?landscape and parse the urle and set the orientation?
i’m not able to do this but i think will be very usefull.
thanks
enrico
Yes its possible to apply a transform to the view and rotate to landscape but I won’t be getting to that in the near future.
Thank you for your answer.
i’m trying to understand how pass a parameter to the childBroswer plugin for setting
the device orientation for this new view. In my project only for iPad device is allowed only the portrait orientation and force to landscape or remain in portrait when the the chldBrowser is open and i tried to move in this way, maybe you can add only the missing part!
Thank you for your time!
Cheers
Enrico
i modified in the html page the call to childBroswer in this way
childBrowser.showWebPage(‘localpage.html,landscape’);
in the ChildBrowserCommand split the arguments in this probably tricky and dirty way and change the method
[childBrowser loadURL:url addText:setorientation];
in the ChildBrowserViewController for pass the orientation needed.
in the ChildBrowserViewController at the begin i change this method
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation) interfaceOrientation
for return always the landscape orientation, now i need to test and return the set orientation.
but i do not understand where i can test and set the orientation and how and where i can pass this parameter for test and set the orientation.
ChildBrowserCommand
- (void) showWebPage:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options // args: url
{
if(childBrowser == NULL)
{
childBrowser = [[ ChildBrowserViewController alloc ] initWithScale:FALSE ];
childBrowser.delegate = self;
}
PhoneGapViewController* cont = (PhoneGapViewController*)[ super appViewController ];
childBrowser.supportedOrientations = cont.supportedOrientations;
[cont presentModalViewController:childBrowser animated:YES ];
//split of the string
NSString *str = (NSString*) [arguments objectAtIndex:0];
NSArray *firstSplit = [str componentsSeparatedByString:@","];
NSString *url = [firstSplit objectAtIndex:0];
NSString *setorientation = [firstSplit objectAtIndex:1];
//
if (![url hasPrefix:@"http"])
{
NSURL *appURL = [NSURL URLWithString:url];
if(![appURL scheme])
{
HelloPhoneGapAppDelegate* delegate = (HelloPhoneGapAppDelegate*)[ self appDelegate ];
appURL = [NSURL fileURLWithPath:[[delegate class] pathForResource:url]];
url = [appURL absoluteString];
}
}
[childBrowser loadURL:url addText:setorientation];
}
ChildBrowserViewController
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation) interfaceOrientation
{
return (interfaceOrientation==UIInterfaceOrientationLandscapeRight);
}
- (void)loadURL:(NSString*)url addText:(NSString*)text;
{
if( [url hasSuffix:@".png" ] ||
[url hasSuffix:@".jpg" ] ||
[url hasSuffix:@".jpeg" ] ||
[url hasSuffix:@".bmp" ] ||
[url hasSuffix:@".gif" ] )
{
[ imageURL release ];
imageURL = [url copy];
isImage = YES;
NSString* htmlText = @”";
htmlText = [ htmlText stringByReplacingOccurrencesOfString:@"IMGSRC" withString:url ];
[webView loadHTMLString:htmlText baseURL:[NSURL URLWithString:@""]];
}
else
{
imageURL = @”";
isImage = NO;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[webView loadRequest:request];
}
webView.hidden = NO;
}
Thank you!
Hi,
I’m using phonegap 1.2 and childbrowser plugin, and it doesn’t work, Do I have to downgrade the phonegap version?
Thanks in advance
I haven’t tested the HelloPhoneGap project with PhoneGap 1.2.0 yet — are you seeing any errors in the log?
How do you get the buttons to work in the menu bar at bottom? Are we supposed to add Javascript somewhere?
Regards
Steve Husting
If you are referring to the Done, forward, and back buttons etc — they should just work they are controlled by the ChildBrowserViewController.
When I open a childbrowser it opens in iphone window. How do I set this automatically to open for ipad environment?
The autoresizing mask on the webView in the ChildBrowserViewController.xib file controls this behavior. I have just pushed an update that makes the webView resize appropriately on the iPad. Update and enjoy.
Heidi, thanks for this thread, I’m closer on the CB plugin using your example than any other I’ve found, but am still not there. I am getting 2 errors and think they are related:
On launch –
“iPhone Simulator”,”gap”:”1.2.0″,”version”:”5.0″,”connection”:{“type”:”wifi”}};
2012-01-07 14:10:51.942 ACF1[28958:13403] [INFO] Failed to run constructor: Object:
message = ‘undefined’ is not a function
name = TypeError
When I click on the Open Google button I get a popup saying -
index.html
TypeError: ‘undefined’ is not an object
I have included the plugin in my PhoneGap.plist file. My code:
Head section -
var childBrowser;
function onBodyLoad()
{
document.addEventListener(“deviceready”,onDeviceReady,false);
}
/* PhoneGap has been initialized and is ready to roll */
function onDeviceReady()
{
phoneGapReady.innerHTML = “PhoneGap is Ready”;
childBrowser = ChildBrowser.install();
}
function openChildBrowser(url)
{
try {
//both of these should work…
//window.plugins.childBrowser.showWebPage(url);
childBrowser.showWebPage(url);
}
catch (err)
{
alert(err);
}
}
Body -
…
Open Google
Thanks for your help! Ted
Did you make sure to add the ChildBrowser.js to your html page and to copy the js file in the www/ directory?
Heidi, yes, I include the ChildBrowser.js and added that js file to www root. When I get the chance later today I’ll add the scripts I include in the head, perhaps there is a sequence (or space?) issue. I played with the sequencing a bit but with no luck yet.
The ” Failed to run constructor: Object: message = ‘undefined’ is not a function” error seems to indicate I’m not even getting to the ChildBrowser.install piece, but that’s an assumption on my part. I’ll follow up later with the scripts section, thx!
I have the same issue here !
With a few tests I’ve seen that :
function onBodyLoad() runs well (I’ve put an alert(‘OK!’) in the function)
But if I put the alert in function onDeviceReady() it doesn’t show up, meaning that this function (where plugin installas) doesn’t load !?
Looks like I’m getting through this, I followed this tuto : http://iphonedevlog.wordpress.com/2011/09/24/installing-childbrowser-into-xcode-4-with-phonegap-1-0-mac-os-x-snow-leopard/
But I now have a question : is there a way to force landscape mode ?
I’m in a landscape only iPad app so it feels wrong that ChildBrowser opens in portrait although all the rest is in landscape
Thanks for your help !
Yes — it is possible — if you just want landscape then go into the ChildBrowserViewController.xib file – on the left hand side click on the “view” – on the attributes inspector change the orientation from portrait to landscape.
Hmmmm thanks, I’m on the “View” but don’t really see were are those Attributes …
My bad : saw it, but it’s already in Landscape (I guess because my whole app is in landscape too)
I’ve just read somewhere it may be a bug with the last versions
I’m using PG 1.3.0, Xcode 4.2.1 and the iPad is in 5.0.1
Hello,
is it possible add a function to childbrowser for send by e-mail the diplayed page?
is it possible with phonegap email plugin?
Could be an interesting function i think.
Many thanks!
No suggestion on how / where begin for add this function?
Thanks!!
Hello again,
Finalizing my app at last, the only thing I miss is the possibility to display local (app internal that is) PDF files in ChildBrowser ?
Not sure how to do this so a bit of help would be much appreciated
(this is my first app)
Refering to the end of your article :
As a side note, I also wanted to be able to open local file resources in my ChildBrowser (which it wasn’t able to do before) so I did edit the plugin files to make this happen. If you are interested in the changes – please peruse the ChildBrowserCommand.m file lines 36-44.
I’ve managed to do something but I don’t know why the address automatically changes to a about:blank
I use this link : PDF
(a javascript gets in the head the complete path to be encoded as un URI)
But when I click on that link in the app, i see this in the console :
2012-01-13 14:25:51.830 CRT-D[4644:707] View did load
2012-01-13 14:25:51.835 CRT-D[4644:707] Opening Url : about:blank
2012-01-13 14:25:51.870 CRT-D[4644:707] Opening Url : file:///var/mobile/Applications/32FE8551-284B-45FA-B48B-309809B7CE18/CRT-D.app/www/pdf/Performance-360-Anatomical-Reference-Guide.pdf
2012-01-13 14:25:51.883 CRT-D[4644:707] New Address is : about:blank
What am I missing ? Why does the address changes at the last point before opening as it should ?
Not sure — I can open a PDF in the HelloPhoneGap1.0 just fine. Difference is the two “opening url:” statements — mine only shows one. I would look more closely at the javascript events that you are firing onclick. Maybe you are calling it twice.
Yes I’ve tested your helloPhoneGap and it works in there but not in mine …
I’ve tried to copy paste from your project to mine but still no go
Well, I really not now where to check anymore, so if some one wants a little cash in order to find this issue, just let me know !
ChildBrowser works and opens an external URL as it should, but if I want to open a local PDF file (I’ve tried several stuff found on the web) it loads the file (at least in the log) but immediately changes the address to about:blank
2012-01-13 18:55:26.733 CRT-D[6067:707] View did load
2012-01-13 18:55:26.739 CRT-D[6067:707] Opening Url : about:blank
2012-01-13 18:55:26.773 CRT-D[6067:707] Opening Url : pdf/Performance-360-Anatomical-Reference-Guide.pdf
2012-01-13 18:55:26.784 CRT-D[6067:707] New Address is : about:blank
Did you have some suggestions??
i tried to google but didn’t find nothings.
Thanks!!
Hello Heidi, I implemented this in my iPhone app and it works great. But have a question on this – I’m loading pdf document’s in the child browser and the pdf has some hyperlinks that i want to open in a safari browser (coming out of the app). Is that possible? Currently, they are opening in the child browser itself.