locked
injecting Javascript with WebView.Navigate RRS feed

  • Question

  • Hello,

    I would like to know how to inject Javascript code into W8 sdk WebView. Navigate method wants a Uri. 

    Is this right?

    webView1.Navigate(new Uri("javascript:var s = function() {window.scrollTo(0,0 );  }; s();"));
    


    I wasn't able to find other suitable methods except NavigateToString which I think replace all HTML. Doesn't it?

    Thanks in advance

    Monday, February 6, 2012 5:04 PM

Answers

  • Hi P5,

    There isn't a way to inject bare JavaScript code into a WebView. Navigate requires a Uri to navigate to and will replace the entire page with the contents of that Uri. NavigateToString would be the method to supply the code directly, but as you say it will replace the entire page.

    --Rob


    Monday, February 6, 2012 5:38 PM
    Moderator

All replies

  • Hi P5,

    There isn't a way to inject bare JavaScript code into a WebView. Navigate requires a Uri to navigate to and will replace the entire page with the contents of that Uri. NavigateToString would be the method to supply the code directly, but as you say it will replace the entire page.

    --Rob


    Monday, February 6, 2012 5:38 PM
    Moderator
  • So is it impossible to execute Javascript into a WebVIew? I do not think so. How to do that?  mshtml.HTMLDocument  has scripts but I do not know in W8.
    Monday, February 6, 2012 5:51 PM
  • Can you please explain what you mean by executing JavaScript in a WebView more clearly?

    The WebView control does not provide any direct access to the HTML document. You can navigate to a page including JavaScript either with Navigate or with NavigateToString. You can invoke script within the page with InvokeScript. 

    --Rob

    Tuesday, February 7, 2012 1:29 AM
    Moderator
  • I'm interested in executing Javascript code on the fly as in the above example rather than calling scripts which are already in place. According to what you are saying, however, it seems that the only way to inject Javascript code is to add it to the HTML string representing the page and then returning it to the WebView with NavigateToString after processing it. But I feel it is cumbersome and it needs for the HTML to be extracted before...Is it possible? as it was with mshtml.HTMLDocument.body.innerHTML?


    Tuesday, February 7, 2012 9:41 AM
  • No, there is no way to execute bare JavaScript. You can navigate to a page containing the JavaScript and can InvokeScript JavaScript on the current page.

    --Rob

    Tuesday, February 7, 2012 11:30 PM
    Moderator