2013-12-09 39 views
6

UIWebViewを介してHTMLページが読み込まれています。ユーザーがどのように見えるのリンクを選択した場合:UIWebView:ハイパーリンクから属性を取得

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

を私はhrefの値はNSURLRequestからUIWebViewDelegate方法でクリックを得ることができます:

webView:shouldStartLoadWithRequest:navigationType: 

しかし、私はこのハイパーリンクから属性値を取得する方法(のWebView =」 ")、属性名" webview "が決定されていると仮定していますか?

+0

チェックこの**のhttp: //stackoverflow.com/questions/5775679/how-can-i-get-name-from-link** –

答えて

0

JavaScriptを使用して属性「webview」を取得できます。その後、その属性とその値をネイティブObjective Cコードに送信できます。

HTMLページ内のスクリプトタグに、このJavaScriptコードを追加します。

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

} 

リンク(href属性で&注2)形式に変換されます。 <a webview="2" href="#!/accounts-cards/<%= item.acctno %>&2"></a> 次に、あなたがあなたのコールバックを取得し、あなたのWebViewのparam値を解析することができます

- (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; 
} 
関連する問題