从UIWebView访问元数据

如何访问在iOS中加载到UIWebView的HTML页面的元数据?

您可以通过以下方式访问元标记的内容:

NSString *graphURL = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByName('facebook_share') [0].getAttribute('content')"]; 

您可以在其中更改在“内容”中声明的属性名称

通过注入JavaScript调用 –

  var metas = document.getElementsByTagName('META'); var i; for (i = 0; i < metas.length; i++) { ... } 

在中提取作者

 <html><head> <meta name="Author" content="Bloody Mary"> </head><body></body></html> 

将javascript包装在一个函数中,将其保存为文件reportMeta.js并将其添加到您的项目中。

  // file reportMeta.js function reportMeta(){ alert(document.getElementsByName('author')[0].getAttribute('content')); } 

然后从webViewDidFinishLoad加载文件并执行它:

 - (void)webViewDidFinishLoad:(UIWebView *)webView { NSString *path = [[NSBundle mainBundle] pathForResource:@"reportMeta" ofType:@"js"]; NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; [webView stringByEvaluatingJavaScriptFromString:jsCode]; [webView stringByEvaluatingJavaScriptFromString:@"reportMeta()"]; } 

或者,如果你的JS很短,你可以把它内联在Objective-C中。