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