Make async event synchronous in JavaScript

后端 未结 5 1764
迷失自我
迷失自我 2021-01-14 04:06

I\'m using the WPF 3.5SP1 WebBrowser control to display a page containing some javascript functions. My program then needs to invoke a javascript function which will make an

5条回答
  •  遥遥无期
    2021-01-14 04:49

    Is there a way I can make the first javascript function sleep until something happens (with out locking up the browser)?

    Yes - you can use the asynchronous function as it was intended to be used: pass it a callback, and let it do its thing. You should be able to pass a callback from C# into your JS function, which can then either pass it to your asynchronous function directly, or wrap it in another function if post-processing is required.


    An example of the implementation of a callback - this works with the WinForms WebBrowser control, i haven't tested it with WPF but they should be pretty much the same:

    [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    public class Callback
    {
       // allows an instance of Callback to look like a function to the script
       // (allows callback() rather than forcing the script to do callback.callMe)
       [System.Runtime.InteropServices.DispId(0)]
       public void callMe(string url)
       {
          // whatever you want to happen once the async process is complete
       }
    }
    

    ...

    Callback cb = new Callback();
    WebBrowser.InvokeScript("myscript", new object[] { cb })
    

    ...

    function myscript(callback)
    {
       some_async_function(function()
       {
          // script-specific completion code
          if ( callback )
             callback();
       });
    }
    

提交回复
热议问题