Reputation: 5670
I want to add below content to my webview
<html>
<body>
<h1>My First Heading</h1>
<div id="mydiv" style="width: 100%; height: 100%;" ></div>
<script src="https://mydomain/Embed.js" type="text/Javascript">
</script>
</body>
</html>
My code looks like this
<WebView x:Name="wView"></WebView>
Code behind
wView.NavigateToString(
@"<html> <body> <h1>My First Heading</h1> <div id=""mydiv"" style=""width: 100%; height: 100%;"" ></div> <script src=""https://mydomain/Embed.js"" type=""text/Javascript""> </script> </body> </html>");
With this approach, I am unable to run any javascript inside Embed.js
. Only content inside H1 tag is getting displayed. how can I make sure the javascript inside webview (Embed.js in my case) gets executed?
Upvotes: 1
Views: 150
Reputation: 7727
According to the description of WebView.NavigateToString()
:
NavigateToString supports content with references to external files such as CSS, scripts, images, and fonts. However, it does not provide a way to generate or provide these resources programmatically.
Therefore, a better way to make js effective is to create an HTML file in the project, write your HTML content into it, and use it in the following method:
wView.Source = new Uri("ms-appx-web:///Html/myHtmlFile.html");
If you need to dynamically modify the content of the HTML file, then ms-appx-web
is not appropriate, because it is directed to the files in the package, and the files in the package cannot be modified directly at runtime.
According to this document. You can save the html text in LocalFolder
's subfolder as a temporary file and guide it through ms-appdata:
var htmlFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("html", CreationCollisionOption.OpenIfExists);
var localFile = await htmlFolder.CreateFileAsync("temp.html", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(localFile, html);
wView.Navigate(new Uri("ms-appdata:///local/html/temp.html"));
P.S. Temporary files must be stored in a subfolder of LocalFolder, and there can be no links to the same level
Upvotes: 1