我有一个呈现javascript的UIWebView。每当UIWebView中呈现的javascript关闭时,我想杀死这个UIWebView。
实质上,我想让UIWebView仅用于加载javascript!
答案 0 :(得分:0)
为了执行javascript,您不需要在当前视图上添加uiwebview。你可以在屏幕上显示你的uiwebview来执行你想要的观察者。
通知您的uiwebview关闭自己使用javascript。首先,您必须将您的课程设置为您的uiwebview的代表:
NSURL *url = [NSURL URLWithString:@"https://myWebWithJavascript.html"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//if your are not to display webview, frame dimensions does not mind
UIWebView uiwebview = [[UIWebView alloc] initWithFrame:CGRectMake(0,0,320, 480)];
[uiwebview setDelegate:self]; //remember that your .h has to implement <UIWebViewDelegate>
[uiwebview loadRequest:request];
//then you implement notifications:
//this is executed when uiwebview has been loaded
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//put here code if you wanna do something with uiwebview once has finished loading
}
//this one is executed if your request returns any error on loading page
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
//put here code if you wanna manage html errors
}
//this one it the ONE you will use to receive messages from javascript code:
//this function is executed every time an http request is made
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest: (NSURLRequest*)req navigationType:(UIWebViewNavigationType)navigationType {
//we check every time there is an http request if the request contains
//an special prefix that indicates it is not a real http request, but
//a comunication from javascript code
if ([[[req URL] absoluteString] hasPrefix:@"my-special-frame"]) {
//so thats it- javascript code is indicating me to do something
//for example: closing uiwebview:
[webview release]; //probably it would be cleverer not to kill this way your uiwebview...but it is just an example
return NO; //that is important because avoid uiwebview to load this fake http request
}
return YES; //that means that it will load http request that skips the if clause
}
然后在您的javascript中,您只需要使用我们期望的Objective-c代码的特殊前缀发出http请求:
var iframe = document.createElement("IFRAME");
iframe.setAttribute("src", "my-special-frame:uzObjectiveCFunction");
document.documentElement.appendChild(iframe);
在这个例子中,我打开一个带有包含我们特殊前缀的URL的框架。你也可以做一个简单的事情:
document.location.href = my-special-frame:uzObjectiveCFunction;
希望这有助于你的疑惑!祝好运!