Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cefsharp winforms: Inject jquery into page

I'm using ChromiumWebBrowser to load a website, and after page loaded, I'll execute some script

browser.ExecuteScriptAsync(script)

But that website not use jquery, so difficult to code my script. I want to inject jquery into that site to write my script easier. How can I do it? Thank you very much

EDIT:

I have had a jquery file in my computer. And I would like to add it to the page where I want to crawl data. I tried using LoadingStateChanged event, but not worked.

private void Browser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
{
    ChromiumWebBrowser browser = (ChromiumWebBrowser)sender;
    lbStatus.SetText(e.IsLoading ? "Loading..." : browser.Address);
    if (!e.IsLoading)
    {
        //Load jquery
    }
    else
    {

    }
}
like image 528
Minh Giang Avatar asked May 03 '16 08:05

Minh Giang


2 Answers

Set this code to script variable as string and then call browser.ExecuteScriptAsync(script)

(function () {
    // more or less stolen form jquery core and adapted by paul irish
    function getScript(url, success) {
        var script = document.createElement('script');
        script.src = url;
        var head = document.getElementsByTagName('head')[0],
            done = false;
        // Attach handlers for all browsers
        script.onload = script.onreadystatechange = function () {
            if (!done && (!this.readyState
                || this.readyState == 'loaded'
                || this.readyState == 'complete')) {
                done = true;
                success();
                script.onload = script.onreadystatechange = null;
                head.removeChild(script);
            }
        };
        head.appendChild(script);
    }
    getScript('http://code.jquery.com/jquery-latest.min.js', function () {
        if (typeof jQuery == 'undefined') {
            console.log('Sorry, but jQuery wasn\'t able to load');
        } else {
            console.log('This page is now jQuerified with v' + $.fn.jquery);

            $(document).ready(function () {
                alert(1);
                //here you can write your jquery code
            });
        }
    });
})();
like image 120
amirpaia Avatar answered Sep 18 '22 23:09

amirpaia


i push the entire jquery js-file as inline-code and works great:

browser.ExecuteScriptAsync(File.ReadAllText(@"content\jquery.1.11.1.min.js"));

reduces loading times...

like image 45
MaxKlaxx Avatar answered Sep 22 '22 23:09

MaxKlaxx