Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject JQuery into existing page within a UIWebView?

I am trying to inject JQuery into a UIWebView of a page that I can't control, say Google, for example. When a UITextField gets focus, I am executing the following lines of code:

NSString* scriptInject = @"var headElement = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); 
    script.setAttribute('src','http://jquery.com/src/jquery-latest.js');
    script.setAttribute('type','text/javascript'); headElement.appendChild(script);";
    [myWebView stringByEvaluatingJavaScriptFromString:scriptInject];    
    [myWebView stringByEvaluatingJavaScriptFromString:@"$(document).ready(function() {$('body').css('background', '#FF0000');}"];

I am executing the background change to validate that I am able to run a JQuery script. I can verify that the Objective-C method is being called, and I even planted an alert for the onload of the newly created <script> tag, so I know that it is being executed in the UIWebView. How do I inject it correctly that I can execute it?

EDIT:

I have event tried this after calling the function to change the color:

[myWebView stringByEvaluatingJavaScriptFromString:@"alert($('body').css());"];

No alert shows.

like image 549
Wayne Hartman Avatar asked Aug 20 '10 00:08

Wayne Hartman


2 Answers

This has worked for me:

NSString *jqueryCDN = @"http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js";
NSData *jquery = [NSData dataWithContentsOfURL:[NSURL URLWithString:jqueryCDN]];
NSString *jqueryString = [[NSMutableString alloc] initWithData:jquery encoding:NSUTF8StringEncoding];
[webView stringByEvaluatingJavaScriptFromString:jqueryString];

[webView stringByEvaluatingJavaScriptFromString:/*jquery commands here*/];

Taken from this article.

like image 90
Stunner Avatar answered Oct 03 '22 14:10

Stunner


If jQuery is not in the DOM already you can use stringByEvaluatingJavaScriptFromString: to inject it. I've had similar problem, I wrote a blog post about it: HTML parsing/screen scraping in iOS.

like image 23
Benedict Cohen Avatar answered Oct 03 '22 16:10

Benedict Cohen