How to inject Javascript in the WP7 WebBrowser control?

狂风中的少年 提交于 2019-12-17 09:57:58

问题


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.


回答1:


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... ");



回答2:


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.



来源:https://stackoverflow.com/questions/8348503/how-to-inject-javascript-in-the-wp7-webbrowser-control

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!