最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - CefSharp - Get result of AJAX request - Stack Overflow

programmeradmin2浏览0评论

I am really new to CefSharps Chromium browser and have difficulty figuring out how to get the result of a jquery ajax request.

My first attempt was to pass my AJAX requesto to EvaluateScriptAsync. In fact the script works. It does exactly what I want, but I do not get any results/status codes, because my Cef-Task does not wait until AJAX has pleted its work.

Here an example (just a sample code):

var tasks = pdBrowser.EvaluateScriptAsync(@"
    (function(){
        $.ajax({
            type: ""POST"",
            dataType: ""json"",
            cache: false,
            url: ""_resources/php/ajaxRequests.php"",
            async: false,
            data: {
                action: ""insertCrossPlatform"",
                type: """",
                values: JSON.stringify(""foo bar"")
            },
            success: function(response) {
                if (typeof response === 'string' && response.substring(0, 5) == ""ERROR"")
                {
                    return response;
                }
                    else
                {
                    //pageReload();
                    return ""OK"";
                }
            },
            error: function(xhr, textStatus, errorThrown) {
                return errorThrown + ""\n"" + xhr.responseText;
            },
            plete: function() {
                return ""COMPLETE"";
            }
        });
    })();", null);

tasks.ContinueWith(t =>
{
     if (!t.IsFaulted)
    {
        var response = t.Result;
        if (response.Success)
        {
            if (response.Result != null)
            {
                MessageBox.Show(response.Result.ToString());
            }
        }
        else
        {
            MessageBox.Show(response.Message, "Ein Fehler ist aufgetreten", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
    }
}, TaskScheduler.Default);

Afterwards I have read that there is a SchemeHandler, but I do not properly understand how to implement it. Can anyone help me out?

Thanks in advance.

I am really new to CefSharps Chromium browser and have difficulty figuring out how to get the result of a jquery ajax request.

My first attempt was to pass my AJAX requesto to EvaluateScriptAsync. In fact the script works. It does exactly what I want, but I do not get any results/status codes, because my Cef-Task does not wait until AJAX has pleted its work.

Here an example (just a sample code):

var tasks = pdBrowser.EvaluateScriptAsync(@"
    (function(){
        $.ajax({
            type: ""POST"",
            dataType: ""json"",
            cache: false,
            url: ""_resources/php/ajaxRequests.php"",
            async: false,
            data: {
                action: ""insertCrossPlatform"",
                type: """",
                values: JSON.stringify(""foo bar"")
            },
            success: function(response) {
                if (typeof response === 'string' && response.substring(0, 5) == ""ERROR"")
                {
                    return response;
                }
                    else
                {
                    //pageReload();
                    return ""OK"";
                }
            },
            error: function(xhr, textStatus, errorThrown) {
                return errorThrown + ""\n"" + xhr.responseText;
            },
            plete: function() {
                return ""COMPLETE"";
            }
        });
    })();", null);

tasks.ContinueWith(t =>
{
     if (!t.IsFaulted)
    {
        var response = t.Result;
        if (response.Success)
        {
            if (response.Result != null)
            {
                MessageBox.Show(response.Result.ToString());
            }
        }
        else
        {
            MessageBox.Show(response.Message, "Ein Fehler ist aufgetreten", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
    }
}, TaskScheduler.Default);

Afterwards I have read that there is a SchemeHandler, but I do not properly understand how to implement it. Can anyone help me out?

Thanks in advance.

Share Improve this question asked May 10, 2016 at 14:20 IamninoIamnino 3801 gold badge4 silver badges19 bronze badges 1
  • If you returned a value in your anonymous closure then that would be returned as the result of EvaluateScriptAsync. You could return the params as json, then execute a WebRequest in C#, when plete execute more JS to update your UI. I don't particularly remend this approach, see alternatives below. – amaitland Commented May 10, 2016 at 21:54
Add a ment  | 

3 Answers 3

Reset to default 2

Firstly SchemeHandler is unlikely to be suitable in this scenario, you would typically implement a SchemeHandler when your providing the response.

Most people choose to bind an object, and call a method on their bound object when they wish to municate with the parent application. See the FAQ for an example. https://github./cefsharp/CefSharp/wiki/Frequently-asked-questions#3-how-do-you-expose-a-net-class-to-javascript

With 49.0.0 you can implement ResponseFilter to gain access to the underlying response buffer, it's plex and not well documented, so if your not fortable digging through reference C++ code then this option isn't for you. Here's a reference https://github./cefsharp/CefSharp/blob/cefsharp/49/CefSharp.Example/Filters/PassThruResponseFilter.cs#L17

Something that I did was create an element on the page through javascript with an ID that is the response of the ajax call. So for example, when you make an ajax call assign an ID to the ajax call.

When the ajax call returns, write an element on the page with the pre-assigned id and callback information. Then you can just use cefsharp to read the element content from the page and this will be your callback information.

var myDivElement =document.getElementById('textareaInfo');

if( myDivElement === null)
{
var input = document.createElement('textarea'); 
input.id = "textareaInfo";
input.value = "Test"
input.rows="4";
input.cols="50";
input.style="height:100%;width:900px;"

var dom = document.getElementsByClassName("page-body")[0];
dom.insertAdjacentElement('afterbegin', input)
}

Then later with ajax

var root = 'https://jsonplaceholder.typicode.';

var _holder = callbackObj;

callbackObj.showMessage(""ajax"");

$.ajax({

  url: root + '/posts/1',
 contentType: 'application/json; charset=utf-8',
  method: 'GET',
plete: function(data){

},
 success: function(response) {

     $(#'textareaInfo').value(response);                
                        }
}).then(function(data) {
   callbackObj.showMessage(data);
});

Then read the texarea from cefsharp in c#

chromeBrowser.GetMainFrame().EvaluateScriptAsync(function()...$(textareaInfo).value).Result

You can use PostMessage javascript method to notify .NET application:

CefSharp.PostMessage('Your data Here');

Here is .NET code example for headless browser:

var browser = new ChromiumWebBrowser("", null, RequestContext);
browser.JavascriptMessageReceived += (sender, e) =>
            {
                if ((string)e.Message.notificationid == "notification1")
                {
                    // Your processing code goes here
                }
            };

browser.Load(destinationUrl);
browser.ExecuteScriptAsync("(function() { ... ; CefSharp.PostMessage({data: data, notificationid: 'notification1'});})()");
发布评论

评论列表(0)

  1. 暂无评论