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:

  1. call functions programically
  2. 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

  1. search file know there, such as: <script lang=\"en-us\" type=\"text/javascript\">
  2. using string manipulation, add desired text, such function (but can anything)
  3. 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

Popular posts from this blog

javascript - How to process users in one specific order using map o each function? -

java - Two interface have same method name with different return type -

javascript - Linking from page A to a specific iframe on page B -