我想使用UIWebView从我的iPhone应用程序执行javascript代码。
但是只有html部分正在执行而javascript部分没有执行。它也没有显示错误。
NSMutableString *htmlCode = [NSMutableString stringWithString:@"<!DOCTYPE HTML>"];
[htmlCode appendString:@"<html><head><tilte> sadaf </title>"];
[htmlCode appendString:@"<h1>My First Web Page</h1>"];
[ htmlCode appendString:@" <p id='demo'>This is a paragraph.</p>"];
[self.webView loadHTMLString:htmlCode baseURL:nil];
webView.delegate= self;
[webView stringByEvaluatingJavaScriptFromString:@"<script type='text/javascript'>document.getElementById('demo').innerHTML=Date();</script> "];
答案 0 :(得分:1)
如果您使用stringByEvaluatingJavaScriptFromString
来评估JavaScript,那么您不需要将JavaScript代码包装在<script>
标记中(事实上,这样做会阻止您的脚本执行)。试试这个:
[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById('demo').innerHTML=Date();"];
答案 1 :(得分:0)
检查委托是否设置正确。
- (void)viewDidLoad
{
[super viewDidLoad];
// init and create the UIWebView
webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 88, 320, 400)];
webView.autoresizesSubviews = YES;
webView.autoresizingMask=(UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth);
[webView setDelegate:self];//set the web view delegates for the web view to be itself
NSMutableString *htmlCode = [NSMutableString stringWithString:@"<!DOCTYPE HTML>"];
[htmlCode appendString:@"<h1>My First Web Page</h1>"];
[htmlCode appendString:@" <p id='demo'>This is a paragraph.</p>"];
[htmlCode appendString:@"</form> </body> </html> "];
[self.webView loadHTMLString:htmlCode baseURL:nil];
[self.view addSubview:webView];//add the web view to the content view
}
- (void) webViewDidFinishLoad:(UIWebView *)webView1
{
NSLog(@"webViewDidFinishLoad");
[webView1 stringByEvaluatingJavaScriptFromString:@"alert('hi');document.getElementById('demo').innerHTML=Date();"];
}
这可能有所帮助!