Webview jQuery insert

Viewed 313

I have a project in Xamarin where I have a webview (Renderer and other things are implemented in IOS, Android, UWP).

I am trying to insert jQuery into it using the following two methods. It works fine, if I have some other JS file, I can read and execute but it does not work with jQuery.

  1. First using the URL
  2. Reading the whole JS file and inserting it

I can't execute any jQuery function. What am I missing?

// Method 1
private async void btnExecute_Pressed(object sender, EventArgs e) {
    var res = ReadResource("JavaScript1.js", "jQuery(document.body).css('background-color','green');");
    var obj = await webView.EvaluateJavaScriptAsync(res);
}

// Method 2
public async Task<string> LoadJQuery() {
    static string jquery = @"https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js";

    string script = @"
    script = document.createElement('script');";
    script= script + " script.src = '" + jquery+"';";
    script = script + @" var head = document.getElementsByTagName('head')[0];
            head.appendChild(script); ";

    script = Regex.Replace(script, @"\t|\n|\r", "");
    
    await webView.EvaluateJavaScriptAsync(script);
    return "";
}

public string ReadResource(string name, string funcToExecute) {
    var r = ReadResource(name);
    r = Regex.Replace(r, @"\t|\n|\r", "");
    r = r + " " + funcToExecute;
    return r;
}

public string ReadResource(string name) {
    var assembly = Assembly.GetExecutingAssembly();
    var resourceName = "NameSpace.Resource." + name;
    using (Stream stream = assembly.GetManifestResourceStream(resourceName))
    using (StreamReader reader = new StreamReader(stream))
    {
        string result = reader.ReadToEnd();
        return result;
    }
}
0 Answers
Related