2013-12-09 46 views
6

我有通過UIWebView加載的HTML頁面。如果用戶選擇鏈接,看起來像:UIWebView:從超鏈接中獲取屬性點擊

<a webview="2" href="#!/accounts-cards/<%= item.acctno %>"></a> 

我可以得到href的值在UIWebViewDelegate方法點擊來自的NSURLRequest:

webView:shouldStartLoadWithRequest:navigationType: 

但我怎麼能得到這個超級鏈接屬性值(網頁流量=」 「)假設屬性名稱」webview「確定?

+0

檢查這個** HTTP: //stackoverflow.com/questions/5775679/how-can-i-get-name-from-link** –

回答

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. 
     } 
} 
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]; 

} 

鏈接將被轉換成格式(注意:& 2 href屬性): <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; 
}