How to get the address of a linked Stylesheet in webbrowser control - c#

I have a webbrowser control in a C# winform, which loads the following text:
<head>
<link rel="stylesheet" type="text/css" href="d:/git/ArticleScraper/reports/default.css">
</head>
Can I find the address of the css (d:/git/ArticleScraper/reports/default.css) and load it in a textbox editor? It could be a local or online css file with absolute or relative address.
I didn't find any related property or method in the webbrowser control.

WebBrowser control has an event DocumentComplete.
It is triggered once your document/file loading has been completed.
First, register to the event:
webBrowser1.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.WebBrowser1_DocumentCompleted);
In the event callback, search for "LINK" element tag.
private void WebBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var browser = sender as WebBrowser;
var document = browser.Document;
foreach(HtmlElement link in document.GetElementsByTagName("LINK"))
{
// this is your link:
link.GetAttribute("href")
}
}

The following code will help you. This one is using LINQ query
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Navigate(#"D:\DemoFolder\demo.html");
}
private void button1_Click(object sender, EventArgs e)
{
// Get a link
HtmlElement link = (from HtmlElement element in webBrowser1.Document.GetElementsByTagName("link") select element)
.Where(x => x.GetAttribute("rel") != null && x.GetAttribute("rel") == "stylesheet" && x.GetAttribute("href") != null).FirstOrDefault();
if (link != null)
{
// Get CSS path
string path = link.GetAttribute("href");
textBox1.Text = path;
}
}
The following is a screenshot of the output

Related

How can i click on the image button when i know only div id and img src in C#?

I was searching solutions on Stack Overflow but didn't find it so that's new question. I'm making program which will login you into the web game and click to start. Here is problem. I was trying some codes like:
HtmlElementCollection startButton = mapWebBrowser.Document.All;
foreach (HtmlElement start in startButton)
{
if (start.GetAttribute("src") == "/do_img/global/text_tf.esg?l=cs&s=16&t=header_start&f=eurostyle_tbla&color=white&bgcolor=green&h=18")
{
start.InvokeMember("click");
}
}
This doesn't work.
Can you help me? Code of image button is:
<div id="header_start_btn" >
<img src="/do_img/global/text_tf.esg?l=cs&s=16&t=header_start&f=eurostyle_tbla&color=white&bgcolor=green&h=18" />
</div>
And this is full code of my project: Full code
There are a couple of things to consider here. You should set the source in the Form_Load event:
private void Form1_Load(object sender, EventArgs e)
{
mapWebBrowser.Url = new Uri("...");
}
Then you need to wait for the document to render before looking, with the following code:
private void mapWebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
HtmlElement imageTag = mapWebBrowser.Document.GetElementById("header_start_btn").Children[0];
}
Just tested this and it works.

phone:WebBrowser handle mail link

I have a WebBrowser control:
<phone:WebBrowser Name="ArticleContent" Navigating="ArticleContent_Navigating" Navigated="ArticleContent_Navigated" />
And i get article from server like a HTML string:
string Article = "<p>Sometext</p><span style=\"font-family:"Arial","sans-serif";mso-fareast-font-family:"Arial Unicode MS"; mso-fareast-language:LV\">artjomgsd#inbox.lv</span>";
I do this:
ArticleContent.NavigateToString(Article);
And have this function to stop loading icon:
private void ArticleContent_Navigated(object sender, NavigationEventArgs e)
{
HideLoading();
}
And this function to handle links ( to open links in external browser):
private void ArticleContent_Navigating(object sender, NavigatingEventArgs e)
{
e.Cancel = true;
WebBrowserTask webBrowserTask = new WebBrowserTask();
webBrowserTask.Uri = new Uri(e.Uri.ToString(), UriKind.Absolute);
webBrowserTask.Show();
}
My question is, why when i tap E-mail hyperlink nothing hapens? It even doesn't enter ArticleContent_Navigating() function?
P.S. I want to open MailTask on clicking on mail hyperlink.
Unfortunately, mailto: it not supported by the WebBrowser control on Windows Phone.
What you can do is inject Javascript in the HTML that will enumerate all a tags and wire up an onclick event. That event will call window.external.Notify which will in turn raise the ScriptNotify event of the WebBrowser, with the URL as a parameter.
It is a little complicated but I think it's the only option for dealing with the mailto protocol on Windows Phone.
Here is some sample code:
// Page Constructor
public MainPage()
{
InitializeComponent();
browser.IsScriptEnabled = true;
browser.ScriptNotify += browser_ScriptNotify;
browser.Loaded += browser_Loaded;
}
void browser_Loaded(object sender, RoutedEventArgs e)
{
// Sample HTML code
string html = #"<html><head></head><body><a href='mailto:test#test.com'>Send an email</a></body></html>";
// Script that will call raise the ScriptNotify via window.external.Notify
string notifyJS = #"<script type='text/javascript' language='javascript'>
window.onload = function() {
var links = document.getElementsByTagName('a');
for(var i=0;i<links.length;i++) {
links[i].onclick = function() {
window.external.Notify(this.href);
}
}
}
</script>";
// Inject the Javascript into the head section of the HTML document
html = html.Replace("<head>", string.Format("<head>{0}{1}", Environment.NewLine, notifyJS));
browser.NavigateToString(html);
}
void browser_ScriptNotify(object sender, NotifyEventArgs e)
{
if (!string.IsNullOrEmpty(e.Value))
{
string href = e.Value.ToLower();
if (href.StartsWith("mailto:"))
{
EmailComposeTask email = new EmailComposeTask();
email.To = href.Replace("mailto:", string.Empty);
email.Show();
}
}
}
Problem with your Html tag just write Http// before mailto:artjomgsd#inbox.lv\ on your link it will work fine
like bellow
"<p>Sometext</p><span style=\"font-family:"Arial","sans-serif";mso-fareast-font-family:"Arial Unicode MS"; mso-fareast-language:LV\">artjomgsd#inbox.lv</span>";
i tested this code in my application now its work..

How do you click a button in a webbrowser control?

For example, using code and no user input, how would I have my program click the "Search" button on google (assuming I've already filled in the search box and am at google.com)
webBrowser1.Navigate("http://www.google.com");
If you have an ID use this:
webBrowser1.Document.GetElementById("id").InvokeMember("click");
If you have TagName use this
webBrowser1.Navigate("http://www.google.com");
In Web Browser DocumentCompleted event
HtmlElement textElement = webBrowser1.Document.All.GetElementsByName("q")[0];
textElement.SetAttribute("value", "your text to search");
HtmlElement btnElement = webBrowser1.Document.All.GetElementsByName("btnG")[0];
btnElement.InvokeMember("click");
If you have name Class use this:
HtmlElementCollection classButton = webBrowser1.Document.All;
foreach (HtmlElement element in classButton)
{
if (element.GetAttribute("className") == "button")
{
element.InvokeMember("click");
}
}
For adding text in a TextBox to search google.com, use this:
webBrowser1.Document.GetElementById("gs_tti0").InnerText = "hello world";
Try the following code:
public WebBrowser webBrowser1 = new WebBrowser();
private void WebForm_Load(object sender, EventArgs e)
{
try
{
webBrowser1.Height = 1000;
webBrowser1.Width = 1000;
this.Controls.Add(webBrowser1);
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
this.webBrowser1.Navigate("www.google.com.au");
}
catch
{ }
Write down the following function in your c# form:
public void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var webBrowser = sender as WebBrowser;
webBrowser.DocumentCompleted -= WebBrowser_DocumentCompleted;
HtmlElement textElement = webBrowser.Document.All.GetElementsByName("q")[0];
textElement.SetAttribute("value", "mlm company");
HtmlElement btnElement = webBrowser.Document.All.GetElementsByName("btnG")[0];
btnElement.InvokeMember("click");
}
In addition to using InvokeMember and others, if your web page has issues responding when called by ID or Class, you can try using {TAB} & {ENTER} using the SendKeys class within .NET. I've written a lot of scripts for web pages and have found that I've had to use a combination of both (even though SendKeys is far messier than the methods in #AleWin's answer).
Here is the link to the SendKeys class.

How to invoke custom Javascript in System.Windows.Forms.WebBrowser?

I'm loading third party webpage that contains following code
<script type="text/javascript">
onDomReady(function() { some_code1; });
</script>
into WebBrowser component. After some_code1 had executed I need to do some manipulations with Dom that will make some_code1 invalid. The question is how to determine that some_code1 had executed?
I cant't do
private void web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
DoRequiredManipulations();
}
Since this event will occur before some_code1 has executed and will make it invalid.
Also I can't do
private void web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
web.Document.InvokeScript("doSome_code1");
DoRequiredManipulations();
}
Since some_code1 is declared as an anonymous function.
It seems that the only way to do it is this:
private void web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var script = GetScriptText(web.DocumentText);
//execute script in webbrowser
DoRequiredManipulations();
}
The problem is that I don't know how to execute this script in webbrowser. I had tried web.Navigate("javascript: " + script); but it doesn't work correctly.
I found how to do that:
HtmlElement scriptEl = web.Document.CreateElement("script");
(scriptEl.DomElement as IHTMLScriptElement).text = "function myscript() { " + script.Text + " }";
web.Document.GetElementsByTagName("head")[0].AppendChild(scriptEl);
web.Document.InvokeScript("myscript");

Converting HtmlDocument.DomDocument to string

How to convert HtmlDocument.DomDocument to string?
This example is a bit convoluted, but, assuming you have a form called Form1, with a WebBrowser control called webBrowser1, the variable content will contain the markup that forms the document:
private void Form1_Load(object sender, EventArgs e)
{
webBrowser1.Url = new Uri(#"http://www.robertwray.co.uk/");
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var document = webBrowser1.Document;
var documentAsIHtmlDocument3 = (mshtml.IHTMLDocument3)document.DomDocument;
var content = documentAsIHtmlDocument3.documentElement.innerHTML;
}
The essential "guts" of extracting it from the HtmlDocument.DomDocument is in the webBrowser1_DocumentCompleted event handler.
Note: mshtml is obtained by adding a COM reference to 'Microsoft HTML Object Library` (aka: mshtml.dll)
It would be easier to use the HtmlDocument itself, rather than its DomDocument property:
string html = htmlDoc.Body.InnerHtml;
Or even simpler, if you have access to the WebBrowser containing the document:
string html = webBrowser.DocumentText;

Categories