Removing HTML elements from a UIWebView

I was working on a simple app to use UIWebVIews to display pages from a web site. Its a tab bar app and each tab loads a different page from the site.

The site is here: Tech Valley Mobile Developers Network

If you open that link in mobile safari you will see the extra elements added to aid browsing on the smaller screen.

The site is configured with a wordpress plug-in to better handle the mobile browser. The plug-in adds a menu, searching and the ability to toggle the mobile format on and off.

The home page looks like this:

Ios_simulator_screen_shot_feb_8_2012_7

I did not want these elements (the black bits at the top of the web view)  in the app as they would circumvent the tab bar button system.

It turns out, as with most things cocoa, once you figure it out its very simple.

 

The trick is to inject some html into the page after you load it. In this case I injected some javascript to hide content by id <div id=...> tag

 

Here is the code (apologies for the formatting)

- (void)hideUnwantedHTML{

    [self.webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"  

        "script.type = 'text/javascript';"  

        "script.text = \"function hideID(idName) { "  

        "var id = document.getElementById(idName);"  

        "id.style.display = 'none';"

     "}\";" 

 

     "document.getElementsByTagName('head')[0].appendChild(script);"];  

 

    [self.webView stringByEvaluatingJavaScriptFromString:@"hideID('headerbar');"];  

    [self.webView stringByEvaluatingJavaScriptFromString:@"hideID('wptouch-search');"];  

    [self.webView stringByEvaluatingJavaScriptFromString:@"hideID('wptouch-menu');"];  

    [self.webView stringByEvaluatingJavaScriptFromString:@"hideID('drop-fade');"];

    [self.webView stringByEvaluatingJavaScriptFromString:@"hideID('footer');"];    

}

 

What this method does is inject a script to find the element by name (idName) then hide any elements with that name. Call the script once for each id you want to hide.

Call this in your UIWebViewDelegate under the webViewDidFinishLoad: method and the nasty html you don't want will disappear.

 

- (void)webViewDidFinishLoad:(UIWebView *)webView {

    NSLog(@"Finished loading");

    UIApplication *application = [UIApplication sharedApplication];

    application.networkActivityIndicatorVisible = NO;

    [activityIndicator stopAnimating];

    activityIndicator.hidden = YES;

    [self hideUnwantedHTML];

}

 

 

Don't forget to add <UIWebViewDelegate> to your view controller in order to get the delegate calls.

Here is the same UIWebView after the addition of the injected javascript. Nice and clean.

Ios_simulator_screen_shot_feb_8_2012_7

Sure, web apps like this don't make the best apps but when a quick and dirty solution is needed this might just do the trick.