c# - How do I inject javascript code via webview? -
basically want this can't seem find similar webview xaml control. need do, capture incoming json file webview. is, bad request server , unsupported file exception webview. thought injecting javascript alert me, body of incoming json , bypass errors.
there 2 main things can do:
- call functions programically
- inject code using html string
function calling
you can use invokescript
call javascript functions.
if have in webpage script:
<script lang="en-us" type="text/javascript"> function myfunction() { alert("i alert box!"); } </script>
then can in c# call:
mywebview.invokescript("myfunction", null);
which execute script function myfunction
.
injecting text
if download html page , other needed files(using windows httpclient), can inject code manipulating , navigating string.
lets want change above script add function, "helloworld", can
- search file know there, such as:
<script lang=\"en-us\" type=\"text/javascript\">
- using string manipulation, add desired text, such function (but can anything)
- navigate string
the c# code:
string mywebpagestring = getwebpagestring(webpageuri); string scripttagstring = "<script lang=\"en-us\" type=\"text/javascript\">"; int indexofscripttag = mywebpagestring.indexof(scripttagstring); int lengthofscripttag = scripttagstring.length; string insertionscriptstring = "function sayhelloworld() { window.external.notify(\"hello world!\");} "; mywebpagestring = mywebpagestring.insert(indexofscripttag + lengthofscripttag + 1, insertionscriptstring); mywebview.navigatetostring(mywebpagestring);
the result navigated webpage this:
<script lang="en-us" type="text/javascript"> function sayhelloworld() { window.external.notify("hello world!");} function myfunction() { alert("i alert box!"); } </script>
since injection can applied area, html, should able figure out.
hope helps. luck.
this answer based on this msdn blog
Comments
Post a Comment