简体   繁体   中英

InvokeScript not working properly

I'm using WebBrowser to load a page. After it finishes , i'm calling an ajax on that page, but my code doesn't wait for that ajax call to finish ; Here's the code:

Thread thread2 = new Thread(() =>
        {
            WebBrowser browser = new WebBrowser();
            browser.ScrollBarsEnabled = false;
            browser.ScriptErrorsSuppressed = true;

            browser.Navigate("http://localhost/testpdf.html");
            while (browser.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); }
            var d = browser.Document.InvokeScript("$.ajax({type: 'GET', async:false,url: 'http://localhost/test2.html',complete: function (data) {                     $('body').html(d) } }); return $('body').html()"); //ajax
        });
        thread2.SetApartmentState(ApartmentState.STA);
        thread2.Start();
        thread2.Join();

d is always null

When you call InvokeScript , it is intended to execute a function that is already defined in the page's JavaScript. In your case, you are intending to provide new JavaScript, and then invoke it. In order for this to work you either need to define the JavaScript as a function in the page, and then invoke it, or use a built-in function ( eval ) to execute the code for you. This is called "script injection" and is the technique you want to use here. Try eval in this case, like so:

string scriptToRun = "$.ajax({type: 'GET', async:false,url: 'http://localhost/test2.html', success: function (data) { $('body').html(data); }, complete: function () {} }); $('body').html();"; //ajax
var d = browser.Document.InvokeScript("eval", new Object[] { scriptToRun});

Note that I do not "return" the result but rather just list it as the last command, since this is not a function but rather a script to be evaluated. Also note that you want to use a success handler in the $.ajax call, since that is the handler that will get the result. Look at the documentation for jQuery ajax and you will see that complete does not get the parameters you are expecting, although you can include a complete handler if you want to track the status.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM