【问题标题】:UIWebView: get attributes from hyperlink clickedUIWebView:从点击的超链接获取属性
【发布时间】:2013-12-26 12:07:03
【问题描述】:
我通过 UIWebView 加载了 html 页面。如果用户选择如下链接:
<a webview="2" href="#!/accounts-cards/<%= item.acctno %>"></a>
我可以从 NSURLRequest 获取 UIWebViewDelegate 方法中点击的 href 值:
webView:shouldStartLoadWithRequest:navigationType:
但是假设属性名称“webview”已确定,我如何从该超链接 (webview="2") 获取属性值?
【问题讨论】:
标签:
html
ios
objective-c
uiwebview
【解决方案1】:
您可以在 JavaScript 的帮助下获取您的属性“webview”,然后您可以将该属性及其值发送到本机 Objective C 代码。
将此 JavaScript 代码添加到您的 HTML 页面中的脚本标记内:
function reportBackToObjectiveC(string)
{
var iframe = document.createElement("iframe");
iframe.setAttribute("src", "callback://" + string);
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
iframe = null;
}
var links = document.getElementsByTagName("a");
for (var i=0; i<links.length; i++) {
links[i].addEventListener("click", function() {
var attributeValue=links[i].webview; //this will give you your attribute(webview) value.
reportBackToObjectiveC(attributeValue);
}, true);
}
在此之后,您的 webViewDelegate 方法将调用:
- (BOOL)webView:(UIWebView *)wView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
{
if (navigationType == UIWebViewNavigationTypeLinkClicked)
{
NSURL *URL = [request URL];
if ([[URL scheme] isEqualToString:@"callback"])
{
//You can get here your attribute's value.
}
}
【解决方案2】:
您需要更改链接的href。首先注入 javascript 脚本,修补您的链接。
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *js = @"var allElements = document.getElementsByTagName('a');"
"for (var i = 0; i < allElements.length; i++) {"
" attribute = allElements[i].getAttribute('webview');"
" if (attribute) {"
" allElements[i].href = allElements[i].href + '&' + attribute;"
" }"
"}";
[webView stringByEvaluatingJavaScriptFromString:js];
}
链接会被转换成格式(注意href属性中的&2):
<a webview="2" href="#!/accounts-cards/<%= item.acctno %>&2"></a>
然后你可以得到你的回调并解析你的 webview 参数值:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSArray *array = [request.URL.absoluteString componentsSeparatedByString:@"&"];
if (array.count > 2) {
NSLog(@"webview value = %@", array[1]);
}
return YES;
}