Access Meta Data from UIWebView

2020-02-26 02:04发布

问题:

How to access Meta Data of a HTML page loaded into a UIWebView in iOS?

回答1:

You can access the meta tag's content by,

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

where you can change the attribute name declared in 'content'



回答2:

To extract the author in

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

wrap the javascript in a function, save it as file reportMeta.js and add it to your project.

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

Then load the file from webViewDidFinishLoad: and execute it:

- (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()"];
}

Or, if your JS is short you can just inline it inside Objective-C.



回答3:

By injecting javascript calls -

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