Cefsharp Winforms:将jQuery注入页面 [英] Cefsharp winforms: Inject jquery into page

查看:1354
本文介绍了Cefsharp Winforms:将jQuery注入页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ChromiumWebBrowser加载网站,并在页面加载后执行一些脚本

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

browser.ExecuteScriptAsync(script)

但是该网站不使用jquery,因此很难编写我的脚本.我想将jquery注入该站点以更轻松地编写我的脚本.我该怎么做?非常感谢

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

我的计算机上有一个jquery文件.我想将其添加到我要爬网数据的页面中.我尝试使用LoadingStateChanged事件,但没有用.

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
    {

    }
}

推荐答案

将此代码设置为script变量作为字符串,然后调用browser.ExecuteScriptAsync(script)

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

这篇关于Cefsharp Winforms:将jQuery注入页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆