PDA

View Full Version : UIWebView javascript injection


evan
2011-02-11, 11:58
I've been looking at enough blogs so I'm pretty sure how it's coded... but none of them seem to mention where the javascript injection goes in the Obj-C code? Basically all I want to do is get rid of a header on all the pages the user can navigate to (or at least the page that initially loads... I'll worry about subsequent pages later if it's an issue. keep it simple, stupid ;)). Here's the code I have:

[self stringByEvaluatingJavaScriptFromString:@"document.getElementById('login').childNodes[1].innerHTML=''"];

I'm just having a hell of a time finding a place where it should actually work. I attribute it mostly to not fully understanding UIWebView. I figured I'd post this here and then in the meantime read up on how that works and maybe figure it out on my own.

chucker
2011-02-11, 12:18
Send the message to your UIWebView instance, not to self. This page (http://iphoneincubator.com/blog/windows-views/how-to-inject-javascript-functions-into-a-uiwebview), which is the first Google result for "uiwebview javascript", has a few examples. Of note:

You would typically place this line of code in webViewDidFinishLoad.

If you can provide your class, I can give you more concrete pointers. Or I could write a sample project…

evan
2011-02-11, 12:54
Wow, I read over that like 5 times and missed that line every time.

implemented webViewDidFinishLoad: but still not working. I'm doing a test

-(void)webViewDidFinishLoad:(UIWebView *)webView {
[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('login').childNodes[1].innerHTML='';"];
NSString *titel = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
NSLog(@"%@", titel);
}

and only the "1" shows up in the console. no web page title (I've been testing my javascript with the Firebug plugin for firefox).

chucker
2011-02-11, 13:10
Hrm. Virtually identical code works fine for me:

- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSLog(@"%@", [webView stringByEvaluatingJavaScriptFromString:@"document.title"]);
}

Are you setting the delegate to self?

- (void)viewDidLoad
{
[super viewDidLoad];

webView.delegate = self;
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://ix.de"]]];
}

evan
2011-02-11, 14:04
the little things...

works now :)