开发者

UIWebView inserting new <script> into head using stringByEvaluatingJavaScriptFromString

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 UI开发者_如何学PythonWebView.

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜