Because until know what people have been doing are just calling the Script that already exists in the actual webpage.
private void LoadHtml()
{
WebViewControl.Source = new Uri("https://www.twitter.com");
}
First I load a page whose style I would like to modify. I can do this by injecting the CSS file that is available in the local folder of the app.
private async void InvokeScript()
{
// Invoke the javascript function called 'addCSS' that is loaded into the WebView.
try
{
string result = await WebViewControl.InvokeScriptAsync("addCSS", null);
rootPage.NotifyUser($"Script returned \"{result}\"", NotifyType.StatusMessage);
}
catch (Exception ex)
{
string errorText = null;
switch (ex.HResult)
{
case unchecked((int)0x80020006):
errorText = "There is no function called doSomething";
break;
case unchecked((int)0x80020101):
errorText = "A JavaScript error or exception occured while executing the function doSomething";
break;
case unchecked((int)0x800a138a):
errorText = "doSomething is not a function";
break;
default:
// Some other error occurred.
errorText = ex.Message;
break;
}
rootPage.NotifyUser(errorText, NotifyType.ErrorMessage);
}
And then I would call the addCSS function. Of course this won't work since Twitter.com JS Code doesn't have this function.
What I am trying to find out is how to call a JS function which will put a new CSS file into the current webpage in the webview.
What I am trying to find out is how to call a JS function which will put a new CSS file into the current webpage in the webview.
You could make a CSS
file in your project folder, And then use InvokeScriptAsync
method to invoke the JavaScript eval function just like follow.
MyCss.css
body {
background-color:rebeccapurple;
}
Usage
string functionString = "var link = document.createElement('link'); link.rel = 'stylesheet'; link.type = 'text/css'; link.href = 'ms-appx-web:///MyCss.css'; document.getElementsByTagName('head')[0].appendChild(link); ";
await MyWebView.InvokeScriptAsync("eval", new string[] { functionString });
Please note WebView
only supports content in the app package using the ms-appx-web
scheme, and web content using the http
or https
URI schemes. It can't work with assets located in the apps local folder. So using file:///
, ms-appdata:///
or ms-appx:///
scheme won't work here.
User contributions licensed under CC BY-SA 3.0