How to inject Javascript in the WP7 WebBrowser control?

I can inject JavaScript in WebBrowser control in C# windows form by this link

How to inject JavaScript in WebBrowser control?

But I can't do this in WP7, please help me.


Unfortunately WebBrowser.Document is not available on WP7. But you can create and call a JavaScript function using InvokeScript. Have a look over here where I describe how.

In short: you don't use .Document and C# but create a piece of JavaScript instead. You then call eval with this script as parameter to invoke it. Like this:

webBrowser1.InvokeScript("eval", "  ...code goes here... ");

For desktop WebBrowser (WinForms/WPF), at least one <script> tag has to be present on the web page for InvokeScript("eval", ...) to work. I.e., if the page doesn't contain any JavaScript (e.g. <body></body>), eval doesn't work as is.

I don't have Windows Phone SDK/emulator installed to verify if this is also the case with Windows Phone WebBrowser.

Nevertheless, the following works for a Windows Store App. The trick is to use this.webBrowser.InvokeScript("setTimeout", ...) to inject some JavaScript first. I'm using it instead of execScript, which is deprecated since IE11.

async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    // load a blank page
    var tcsLoad = new TaskCompletionSource<object>();
    this.webBrowser.NavigationCompleted += (s, eArgs) =>
        tcsLoad.TrySetResult(Type.Missing);
    this.webBrowser.NavigateToString("<body></body>");
    await tcsLoad.Task;

    // first add a script via "setTimeout", JavaScript gets initialized
    var tcsInit = new TaskCompletionSource<object>();
    this.webBrowser.ScriptNotify += (s, eArgs) =>
    {
        if (eArgs.Value == "initialized")
            tcsInit.TrySetResult(Type.Missing);
    };
    this.webBrowser.InvokeScript("setTimeout", 
        new string[] { "window.external.notify('initialized')", "0" });
    await tcsInit.Task;

    // then use "eval"
    this.webBrowser.InvokeScript("eval", 
        new string[] { "document.body.style.backgroundColor = 'yellow'" });
}

I would appreciate if someone can confirm whether this works or not for WP WebBrowser. LoadCompleted should be used for WP instead of NavigationCompleted in the code above, and WebBrowser.IsScriptEnabled has to be set to true.