views:

116

answers:

1

I am loading an existing html document in a UIWebView with iOS 3.2 on an iPad. After the HTML loads I run the following code to insert jQuery into this document:

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSLog(@"load complete");
if (webView == self.contentView) {

    [self.contentView stringByEvaluatingJavaScriptFromString:
     @"var headID = document.getElementsByTagName(\"head\")[0];"    
     "var newScript = document.createElement('script');"
     "newScript.type = 'text/javascript';"
     "newScript.src = 'jquery-1.4.2.min.js';"
     "newScript.onload=window.location.assign(\"fj://jquery\");"
     "headID.appendChild(newScript);"];

}
NSLog(@"inserting jquery");
}

Then the following code runs when the bogus request for fj://jquery comes:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSLog(@"URL: %@", [[request URL] scheme]);

if ([[[request URL] scheme] compare:@"fj"] == NSOrderedSame) {
    NSString * command = [[request URL] host];

    if ([command compare:@"jquery"] == NSOrderedSame) {
        NSLog(@"got jquery");   

        NSString * offsetStr = [self.contentView stringByEvaluatingJavaScriptFromString:@"$('P:last').offset().top;"];

        NSLog(@"offset: %@", offsetStr);            

    }
    return NO;
}

return YES;
}

As far as I know, this is all pretty much the standard way to insert JS into a loaded HTML in UIWebView.

However, my problem is, that my jQuery code does not run and returns an empty string.

I have used the same code with success in a prototype test app. Now in the real production app, it does not work anymore.

Here is what I have done to isolate the problem, with no success:

  • jquery-1.4.2.min.js is in the same directory as the loaded HTML
  • the webview is not nil
  • when I load the same HTML inside safari and execute the JS code inside the JS console, everything runs as expected

A hint that I have is: the stylesheet.css file in linked in the original document is corrupt (0 KB) but I don't have any control on that. That's how I receive the package form the client. I should be able to work with it.

A: 

I don't know why but the exact problem was apparently that the script elements did not get activated in the first loaded HTML file. Following files were able to use the scripts with no problems.

Engin Kurutepe