Cefsharp winforms: Inject jquery into page

谁都会走 提交于 2019-11-29 22:50:55

问题


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
    {

    }
}

回答1:


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
            });
        }
    });
})();



回答2:


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...




回答3:


it's very easy :)

 string script_1 = "document.getElementsByTagName('head')[0].appendChild(document.createElement('script')).src = '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'";

browser.ExecuteScriptAsync(script_1);

and for call any custom jquery function or class:

 string script_2 = "$('.contact').css('color','#aabbcc');";

 browser.ExecuteScriptAsync(script_2);


来源:https://stackoverflow.com/questions/36999063/cefsharp-winforms-inject-jquery-into-page

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