Lucky Lucky - 1 year ago 74
C# Question

Can't load a local javascript file into the webview

I have a webview inside a uwp application and i need to inject some javascript files into it. I can't include them in the source code of the html page.

This is what I have so far.

private async void WebView_DOMContentLoaded(WebView sender, WebViewDOMContentLoadedEventArgs args)
{
await Webview.InvokeScriptAsync("eval", new string[]
{
"var script = document.createElement('script'); script.type='text/javascript'; script.charset='UTF-8'; script.src ="
+ "'ms-appx://Apps.Webapp/JS/jquery-3.2.1.min.js'"
+ ";document.body.appendChild(script);"
});
}


But when i try with the direct invocation the files are simple not loaded

Anyone has any thoughts that can help me?

Edit: I have tried with no luck

"'ms-appx-web://Apps.Webapp/JS/jquery-3.2.1.min.js'"

Answer Source

After some trial and error I got a working solution:

private async void WebView_DOMContentLoaded(WebView sender, WebViewDOMContentLoadedEventArgs args)
{    
   string scriptToLoad = File.ReadAllText("Apps.Webapp/JS/jquery-3.2.1.min.js");
   string[] arguments = { scriptToLoad };
   await WebBrowserWizzio.InvokeScriptAsync("eval", arguments);
}

This way i'm injecting the whole script into the page and not only the path.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download