我通过UIWebView加载了html页面。如果用户选择的链接如下:
<a webview="2" href="#!/accounts-cards/<%= item.acctno %>"></a>
我可以从NSURLRequest的UIWebViewDelegate方法中点击href值:
webView:shouldStartLoadWithRequest:navigationType:
但是假设属性名称“webview”已确定,我如何从此超链接(webview =“ 2 ”)获取属性值?
答案 0 :(得分:0)
您可以在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.
}
}
答案 1 :(得分:0)
您需要更改链接的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属性中的注释&amp; 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;
}