Search code examples
iosxamarinwebviewxamarin.iosuiwebview

Xamarin iOS UIWebView: How to get custom data attribute values from URL content?


For my Xamarin iOS app, I want to get the custom attribute value present in the URL content provided to the UIWebView.

URL CONTENT:

<html>
<head>
<style>
.democlass {
    color: red;
}
</style>
</head>
<body>
<div id="frame" data-link="LINKER"></div>

<p id="demo"></p>

<button>Try it1</button>
<button>Try it2</button>
<p id="demoz"></p>
<button>Try it3</button>

</body>
</html>

Xamarin iOS:

var webView = new UIWebView();
webView.LoadRequest(new NSUrlRequest(new NSUrl(" */above html page/*")));
var url = webView.EvaluateJavascript("document.getElementsByName('div')[0].getAttribute('data-link')");

when I run the EvaluateJavascript on the UIWebview, I expect the url parameter to fetch the value LINKER but it is returning empty string.

Can anyone help me out? I am not sure what I'm missing or doing wrong.


Solution

  • The correct way :

    var url = webView.EvaluateJavascript("document.getElementById('frame').getAttribute('data-link');");
    

    PS:Make sure this line execute when the webview has finished loading.

    My code :

    public override void ViewDidLoad()
    {
        base.ViewDidLoad();
        var webView = new UIWebView();
        webView.LoadRequest(new NSUrlRequest(new NSUrl(" */above html page/*")));
        web.Delegate = new myDelegate();
    }
    
    public class myDelegate : UIWebViewDelegate
    {
        public override void LoadingFinished(UIWebView webView)
        {
            var str = webView.EvaluateJavascript("document.getElementById('frame').getAttribute('data-link');");
        }
    }