0

我有一个UIWebView包含带有 JS 功能的按钮,但委托方法仅在加载页面上调用,而不是在按下的按钮上,正如我所期望的那样。

问题是什么?

附言

我正在模拟器上测试。

在.h中:

@interface MyViewController : UIViewController <UIWebViewDelegate>{
    UIWebView *webView;
}
@property (strong, nonatomic) IBOutlet UIWebView *webView;

以 .m 为单位:

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString *myHTML = @"<!DOCTYPE html><html><head><script type=\"text/javascript\">
    function myFunction(){document.location = \"myapp:\" + \"myfunction:\" 
    + param1 + \":\" + param2;}</script></head><body><button onclick=\
    "myFunction()\">Try it</button><p>By clicking the button above,
     a function will be called.</p></body></html>";

    [webView loadHTMLString:myHTML baseURL:nil];
    webView.delegate = self;
}


- (BOOL)webView:(UIWebView *)webView2 
shouldStartLoadWithRequest:(NSURLRequest *)request 
 navigationType:(UIWebViewNavigationType)navigationType {

    NSString *requestString = [[request URL] absoluteString];
    NSArray *components = [requestString componentsSeparatedByString:@":"];

    if ([components count] > 1 && 
        [(NSString *)[components objectAtIndex:0] isEqualToString:@"myapp"]) {
        if([(NSString *)[components objectAtIndex:1] isEqualToString:@"myfunction"]) 
        {

            NSLog([components objectAtIndex:2]); // param1
            NSLog([components objectAtIndex:3]); // param2
            // Call your method in Objective-C method using the above...
        }
        return NO;
    }

    return YES; // Return YES to make sure regular navigation works as expected.
}
4

1 回答 1

0

以这种方式测试,对我有用

NSString *myHTML = @"<!DOCTYPE html><html><head>" "<script type='text/javascript'>function myFunction(){alert('ciao');document.location = 'myapp:myfunction:param1:param2';}
</script>"
"</head><body><button onclick='myFunction()'>Try it</button>" 
"<p>By clicking the button above,a function will be called.</p></body></html>";

你的错误应该如下

document.location = \"myapp:\" + \"myfunction:\" + param1 + \":\" + param2;

你应该改写

document.location =\"myapp:myfunction:param1:param2\";
于 2012-07-22T10:30:39.557 回答